C# 带有标量变量的SQL查询不填充Datagridview
我有一个datadridview,它显示SQL数据库表中的数据。在这里,我使用了SQLDataAdapter和DataTable()。请参考下面的代码片段C# 带有标量变量的SQL查询不填充Datagridview,c#,sql,datagridview,ado.net,C#,Sql,Datagridview,Ado.net,我有一个datadridview,它显示SQL数据库表中的数据。在这里,我使用了SQLDataAdapter和DataTable()。请参考下面的代码片段 private void btnSrcDataID_Click(object sender, EventArgs e) { try { dgvInsertInfo.Refresh(); SqlComm = n
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查询字符串或SqlAdapt.Fill(),但我无法理解这个问题。你能找个人帮我一下吗
谢谢,
Chiranthaka事实上,在我的例子中,错误是由于将值传递给标量变量@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中正确填充
谢谢。您在
SqlDataTable
中有任何数据吗?SqlDataTable应该存储数据库表MyDataTable中的数据,并且应该根据SqlComm.CommandText=()中的查询字符串进行筛选。但是我没有得到任何数据。我尝试了下面的代码片段作为SQL语句,但是没有得到结果SqlComm.CommandText=“从MyDataTable中选择*,其中(数据ID类似@SDataID)”;SqlComm.Parameters.AddWithValue(“@SDataID”,txtDataID.Text)
您可以添加您的MyDataTable
的结构和列的类型吗