根据选择的单选按钮显示数据库值

时间:2012-07-26 17:11:43

标签: c# asp.net

我想根据选择的单选按钮在gridview中显示数据库值。我目前正在使用RadioButtonList,我应该根据他们在单选按钮中选择的交易日期显示某些交易。例如,如果他们选择查看过去1个月的事务,我的gridview将仅显示过去一个月的事务。我目前正在使用C#。

根据系统日期检索日期,并在进行交易时记录日期。我可以知道如何使用gridview将无线电事务与数据库联系起来吗?

enter image description here enter image description here

这是我对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();

2 个答案:

答案 0 :(得分:0)

鉴于我看不到你的任何代码:

在RadioButtonList的OnSelectedIndexChanged事件中,您可以使用RadioButtonList1.SelectedItem.Value

选择选择了哪个单选按钮

然后,您可以使用Sql查询来获取结果并将其绑定到您的Datagrid

示例:

//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
}

答案 1 :(得分:0)

尝试这样的事情:

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;
}

这会将表格与数据网格相关联:

dataGridView1.DataSource = table;

基于您的代码的示例:

您可以像这样获得当前日期:

DateTime date = DateTime.Now;

您的sql命令将变为:

SqlCommand cmd = new SqlCommand("SELECT thDate, thType, thAmountIn, thAmountOut from [Transaction] WHERE thDate = " + date + " ORDER BY thDate, thType, thAmountIn, thAmountOut DESC", myConnection); 

您可以像这样实现if语句:

if(radioButton1.Checked == true)
{
cmd += " WHERE thDate = " + date + ";
}
相关问题