【问题标题】:How to use SqlDataSource with button on click to get results from gridview如何使用带有单击按钮的 SqlDataSource 从 gridview 获取结果
【发布时间】:2014-06-17 13:09:54
【问题描述】:

我的总体目标是能够在我的文本框中输入信息并单击按钮以使用 gridview 从数据库中搜索和获取结果。到目前为止,我已经设置了我的SqlDataSource SQL 语句。我需要弄清楚如何将我的点击事件按钮与我的SqlDataSourceTextbox 链接起来。

这是我目前所拥有的:

 protected void Button1_Click(object sender, EventArgs e)
 {
     SqlConnection connection = new SqlConnection("Data Source=********;Initial Catalog=*******;User ID=*******;Password=*******");
     connection.Open();
 }

我不知道如何使用我已经设置的SqlDataSource

更新代码:

SqlConnection sqlCon = new SqlConnection("*******");
        SqlDataAdapter dt = new SqlDataAdapter();
        DataSet ds = new DataSet();
        try
        {
            sqlCon.Open();
            dt.SelectCommand = new SqlCommand("SELECT* FROM  Core.Form_Section_SubSection_Item_Rel WHERE ([DataCollectionPeriodID] = @DataCollectionPeriodID)", sqlCon);
            dt.Fill(ds);
            sqlCon.Close();
            GridView1.DataBind();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

【问题讨论】:

  • 您是否使用存储过程获取数据?
  • @paabobo 否 只是一个简单的 SQL select from where 语句

标签: sql sql-server button gridview sqldatasource


【解决方案1】:

我会建议你使用带有参数的存储过程并执行以下操作,但你可以将其更改为使用你的选择查询,只需更改命令类型

  using (SqlConnection sqlCon = new SqlConnection("connection string")) 
{ 

 using (SqlCommand cmd = new SqlCommand()) 
{ 
 sqlCon.Open(); 
 cmd.Connection = sqlCon; 
  cmd.CommandType = CommandType.Text; 
 cmd.CommandText = "SELECT* FROM Core.Form_Section_SubSection_Item_Rel WHERE         DataCollectionPeriodID = @DataCollectionPeriodID"; 
 cmd.CommandTimeout = 30; 
cmd.Parameters.Add("@DataCollectionPeriodID", SqlDbType.VarChar).Value = TextBox1.Text 
SqlDataAdapter dt = new SqlDataAdapter(cmd); 
DataSet ds = new DataSet(); 
 dt.Fill(ds); 

if (ds.Tables.Count > 0) 
{ 
 if (ds.Tables[0].Rows.Count > 0) 
 { 
 GridView1.DataSource = ds; 
  GridView1.DataBind(); 
 } 
} 
 } 
 }

【讨论】:

  • 好的,所以我将其更改为使用我的 selectquery,但 gridview 没有改变。
  • 你在做 gridview.DataBind 之前没有设置 gridview.DataSource = ds
  • 在我的 GridView 属性中 DataSourceID 已经设置,当我运行它时,它说 DataSource 和 DataSourceID 不能同时使用。
  • 取出datasouceid,直接做datasource
猜你喜欢
  • 1970-01-01
  • 2015-07-30
  • 2014-04-25
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-16
  • 2020-11-22
相关资源
最近更新 更多