C# 如何显示正确的数据?
我有两个datagridview现在我想在第一个datagridview中选择一个名为“Name”的列,并将其作为查询中的WHERE,从表中选择值并将其放入另一个datagridview中C# 如何显示正确的数据?,c#,sql,C#,Sql,我有两个datagridview现在我想在第一个datagridview中选择一个名为“Name”的列,并将其作为查询中的WHERE,从表中选择值并将其放入另一个datagridview中 SqlCommand cmd = new SqlCommand(); cmd = ss.CreateCommand(); foreach (DataGridViewRow row in dgvAtt.Rows) { ss.Open(); cmd.CommandTyp
SqlCommand cmd = new SqlCommand();
cmd = ss.CreateCommand();
foreach (DataGridViewRow row in dgvAtt.Rows)
{
ss.Open();
cmd.CommandType = CommandType.Text;
string Query = "SELECT Signature FROM TBL_Student WHERE Name = '" +
row.Cells[4].Value.ToString() + "' ";
cmd.CommandText = Query;
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter dp = new SqlDataAdapter(cmd);
dp.Fill(dt);
dgvSign.DataSource = dt;
ss.Close();
}
但是当有空值时它会给我错误,并且它只选择第一个datagridview中的第一行。您在每个
foreach
-循环中创建一个新的DataTable
,因此它总是只有一个值。因此,必须在foreach循环之前创建它
SqlCommand cmd = new SqlCommand();
cmd = ss.CreateCommand();
foreach (DataGridViewRow row in dgvAtt.Rows)
{
ss.Open();
cmd.CommandType = CommandType.Text;
string Query = "SELECT Signature FROM TBL_Student WHERE Name = '" +
row.Cells[4].Value.ToString() + "' ";
cmd.CommandText = Query;
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter dp = new SqlDataAdapter(cmd);
dp.Fill(dt);
dgvSign.DataSource = dt;
ss.Close();
}
并确保在使用前检查要使用的值。
有了这个简单的if
-条件,就不会有任何问题了
Edit1:
这个代码片段工作得很好。
只需更改连接字符串即可
DataTable dt = new DataTable();
string error;
using (SqlConnection con = new SqlConnection(@"Data Source=SERVER;Initial Catalog=DATEBASE; User ID=USERNAME; Password=PASSWORD"))
{
SqlCommand cmd = new SqlCommand();
foreach (DataGridViewRow row in dgvAtt.Rows)
{
string Query = "SELECT Signature FROM TBL_Student WHERE Name = '";
if (row.Cells.Count >= 4 && row.Cells[4].Value != null)
{
Query += row.Cells[4].Value.ToString();
}
Query += "'";
try
{
cmd = new SqlCommand(Query, con);
if (con.State == ConnectionState.Closed)
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
}
catch (Exception ex)
{
error = ex.Message;
}
}
}
dgvSign.DataSource = dt;
在每个foreach
-循环中创建一个新的DataTable
,因此它总是只有一个值。因此,必须在foreach循环之前创建它
并确保在使用前检查要使用的值。
有了这个简单的if
-条件,就不会有任何问题了
Edit1:
这个代码片段工作得很好。
只需更改连接字符串即可
DataTable dt = new DataTable();
string error;
using (SqlConnection con = new SqlConnection(@"Data Source=SERVER;Initial Catalog=DATEBASE; User ID=USERNAME; Password=PASSWORD"))
{
SqlCommand cmd = new SqlCommand();
foreach (DataGridViewRow row in dgvAtt.Rows)
{
string Query = "SELECT Signature FROM TBL_Student WHERE Name = '";
if (row.Cells.Count >= 4 && row.Cells[4].Value != null)
{
Query += row.Cells[4].Value.ToString();
}
Query += "'";
try
{
cmd = new SqlCommand(Query, con);
if (con.State == ConnectionState.Closed)
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
}
catch (Exception ex)
{
error = ex.Message;
}
}
}
dgvSign.DataSource = dt;
尝试了此操作,但未显示数据?为什么?试过了,但没有显示数据?为什么呢?