'Display database value based on which radio button is selected
I am suppose to display the database values in a gridview based on which radio button is selected. I'm currently using a RadioButtonList and I'm supposed to display certain transactions based on the transaction date they select in the radio button. For example, if they select View past 1 Month transaction, my gridview is suppose to show only the past one month transaction. I'm currently using C#.
The date is retrieved base on system date and are recorded when there are transactions made. May I know how to link the radio transaction with the database using gridview ?


This is my coding for the gridview.
myConnection.ConnectionString = strConnectionString;
SqlCommand cmd = new SqlCommand("SELECT thDate, thType, thAmountIn, thAmountOut from [Transaction] ORDER BY thDate, thType, thAmountIn, thAmountOut DESC", myConnection);
myConnection.Open();
SqlDataReader reader1 = cmd.ExecuteReader();
GridView1.DataSource = reader1;
GridView1.DataBind();
Solution 1:[1]
Given that I cannot see any code of yours:
On OnSelectedIndexChanged event of the RadioButtonList you can pick up which radio button was selected using RadioButtonList1.SelectedItem.Value
Then you can make a Sql query using to get the results back and bind it to your Datagrid
Example :
//This is the method for event OnSelectedIndexChanged
void Index_Changed(Object sender, EventArgs e)
{
//RadioButtonList1.SelectedItem.Value use the value
and to built as sql query string on your sqldatasource
//Execute
//attach datasource to datagrid
//Databind datagrid
}
Solution 2:[2]
Try something like this:
DataTable table= new DataTable("table");
using (SqlConnection sqlConn = new SqlConnection(@"Your Connection Stuff;"))
{
if (radioButton1.Checked == true)
{
using (SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM yourdatabase WHERE date = " + date, sqlConn))
{
da.Fill(table);
}
dataGridView1.DataSource = table;
}
This links the table to the data grid:
dataGridView1.DataSource = table;
Example based on your code:
You can get the current date like this:
DateTime date = DateTime.Now;
Your sql command would become:
SqlCommand cmd = new SqlCommand("SELECT thDate, thType, thAmountIn, thAmountOut from [Transaction] WHERE thDate = " + date + " ORDER BY thDate, thType, thAmountIn, thAmountOut DESC", myConnection);
You can implement the if statements like so:
if(radioButton1.Checked == true)
{
cmd += " WHERE thDate = " + date + ";
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | HatSoft |
| Solution 2 |
