我一直想知道如何安静很长时间如何在我的datagridview“dtg_ksluzby”中设置我的SqlDataReader以填充列“pocet”。我认为我的代码应该是这样的:
SqlCommand novyprikaz2 = new SqlCommand("SELECT pocet FROM klisluz WHERE id='"+vyberradek+"'",spojeni); // I also have column "pocet" in table klisluz, vyberradek is string which selectrs id number
spojeni.Open();
SqlDataReader precti2 = novyprikaz2.ExecuteReader();
if (precti2.Read())
{
dtg_ksluzby.Columns["pocet"]; // this part I need to improve to fill
}
请您帮我改进代码吗? 非常感谢提前。
编辑trippino:
我希望我的描述是理解的,对不起我的弱英语。
答案 0 :(得分:2)
不要使用字符串连接来构建sql命令,(以避免Sql注入和解析问题)
using(SqlConnection spojeni = new SqlConnection(conString))
using(SqlCommand novyprikaz2 = new SqlCommand("SELECT pocet FROM klisluz " +
"WHERE id = @id",spojeni);
{
novyprikaz2.Parameters.AddWithValue("@id", vyberradek);
spojeni.Open();
using(SqlDataAdapter da = new SqlDataAdapter(novyprikaz2))
{
DataTable dt = new DataTable();
da.Fill(dt);
dtg_ksluzby.DataSource = dt;
}
}
使用DataAdapter从数据库加载数据并将此DataAdapter实例传递给DataGridView的DataSource
答案 1 :(得分:1)
使用类似的东西:
for (int i = 0; i < dtg_ksluzby.Rows.Count; i++)
{
var row = dtg_ksluzby.Rows[i];
using(var novyprikaz2 = new SqlCommand("SELECT pocet FROM klisluz WHERE text LIKE @t AND subkey=@s", spojeni))
{
novyprikaz2.Parameters.AddWithValue("@t", row.Cells["text"].Value.ToString());
novyprikaz2.Parameters.AddWithValue("@s", vyberradek);
spojeni.Open();
SqlDataReader precti2 = novyprikaz2.ExecuteReader();
if (precti2.Read())
{
row.Cells["pocet"].Value = precti2["pocet"];
}
}
}