2017-07-19 45 views
0

我有这个datadridview显示SQL数据库表中的数据。在这里我使用了一个SQLDataAdapter和一个DataTable()。请参阅下面的代码片段。具有标量变量的SQL查询不填充数据格式

private void btnSrcDataID_Click(object sender, EventArgs e) 
     { 
      try 
      { 
       dgvInsertInfo.Refresh(); 
       SqlComm = new SqlCommand(); 

       SqlComm.Connection = SqlConn; 

       SqlComm.CommandText = ("SELECT * FROM MyDataTable WHERE DataID = @SDataID"); 
       SqlComm.Parameters.AddWithValue("@SDataID", txtDataID.Text); 
       SqlDataTable = new DataTable(); 

       SqlAdapt = new SqlDataAdapter(SqlComm); 

       //DataSet dsQryDataId = new DataSet(); 
       SqlAdapt.Fill(SqlDataTable); 

       //Passing data to DatagridView 
       dgvInsertInfo.DataSource = SqlDataTable; 

      } 
       catch (Exception ex) 
      { 
       MessageBox.Show(ex.Message); 
      } 
     } 

我认为问题是用SQL QueryString或SqlAdapt.Fill(),但我不明白这个问题。你能请别人帮我解决这个问题吗?

感谢, Chiranthaka

+0

你在'SqlDataTable'中得到了什么数据吗? –

+0

SqlDataTable应该存储来自数据库表MyDataTable的数据,并且应该根据SqlComm.CommandText =()中的查询字符串进行过滤。但我没有收到任何数据。 – ChiranthakaJ

+0

我试过下面的代码片段作为SQL语句,但无法得到结果。 'SqlComm.CommandText =“SELECT * FROM MyDataTable WHERE(DataID LIKE @SDataID)”; SqlComm.Parameters.AddWithValue(“@ SDataID”,txtDataID.Text); ' – ChiranthakaJ

回答

0

其实在我的情况下传递值的标量@SDataID发生时,由于一个错字错误的错误。以便SQL语句的语法是正确的。请参阅下面的正确SQL语句。

private void btnSrcDataID_Click(object sender, EventArgs e) 
     { 
      try 
      { 
       dgvInsertInfo.Refresh(); 

       SqlComm = new SqlCommand(); 
       SqlComm.Connection = SqlConn; 
       SqlComm.CommandText = "SELECT * FROM MyDataTable WHERE (DataID LIKE @SDataID)"; 
       SqlComm.Parameters.AddWithValue("@SDataID", txtSrcDataID.Text); 

       SqlDataTable = new DataTable(); 
       SqlAdapt = new SqlDataAdapter(SqlComm); 
       SqlAdapt.Fill(SqlDataTable); 

       dgvInsertInfo.DataSource = SqlDataTable; 

      } 
      catch (Exception ex) 
      { 
        MessageBox.Show(ex.Message); 
      } 
     } 

现在数据在DataGridView中正确填充。

谢谢。