我想通过保存按钮通过文本框搜索记录,并在其他文本框中显示搜索的数据,我想看到在选定的数据网格中搜索的行。两个密码我都破解了。但我不能把两个代码混合成一个。很抱歉我的英语不好,这里是我的两个代码
//shows searched row in datagridview but does not show in textboxes
SqlCommand cmd = sqlCon.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from cabphase1 where CODENO='"+txtTNo.Text+"'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
sqlCon.Close();
//2nd code: Shows in textbox but not in datagridview
try
{
SqlCommand cmd = new SqlCommand("Select * from cabphase1 where CODENO = '" + txtCODENOAT.Text + "'", sqlCon);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
txtDNAMEAT.Text = dr[0].ToString();
txtLNOAT.Text = dr[1].ToString();
}
else
{
MessageBox.Show("Enter a valid Taxi CODENO - Eg: 31", "FAILED", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
dr.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error Searching Data" , "Dispatch", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
不需要对数据库执行相同的查询。您也可以使用在第一个操作中检索到的数据显示在文本框中。
也不应该在代码中使用字符串连接来生成SQL查询。这很容易导致SQL注入。强烈建议使用参数化查询来防止SQL注入。
下面的代码使用了参数化查询。
//shows searched row in datagridview but does not show in textboxes
SqlCommand cmd = sqlCon.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from cabphase1 where CODENO = @codeno";
SqlParameter parameter = new SqlParameter("@codeno", System.Data.SqlDbType.NVarChar);
parameter.Value = txtTNo.Text;
cmd.Parameters.Add(parameter);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
sqlCon.Close();
if(dt.Rows.Count > 0)
{
DataRow row = dt.Rows[0];
txtDNAMEAT.Text = row[0].ToString();
txtLNOAT.Text = row[1].ToString();
}
我希望这能帮助你解决你的问题。