关于My project解决方案
问题描述:
亲爱的朋友们,
Dear Friends,
private void textBox1_TextChanged(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=192.168.1.4;Initial Catalog=ParamBills;Persist Security Info=True;User ID=sa;Password=login";
conn.Open();
SqlCommand cmd = new SqlCommand("select Product_Name,Product_Code,Item_Name,Item_code,qty from Master_Stock_Register where Product_Name='" + textBox1.Text + "'", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill (dt);
dataGridView1.DataSource = dt;
// dataGridView1.DataBind();
conn.Close();
}
此解决方案是:当我更改文本框值时,数据网格值也发生了变化..但我需要添加网格下面一个接一个..请帮帮我..
This solution is: when i changed text box value the data grid values also changed.. but i need add one by one below grid.. please help me..
答
在Validated
事件处理程序中执行你的程序而不是在TextChanged
中;正如您已经被告知的那样,每次在TextBox中输入新字符时重新创建数据库连接和查询都是一个设计问题,从用户体验的角度来看,它会使您的应用程序响应性降低并且烦人。
您还应该通过连接从用户获取的值来避免构造SQL查询;这会使您的代码对SQL注入攻击开放。
例如,如果有人在textBox1
中输入以下文本:
Execute your procedure in theValidated
event handler, rather than in theTextChanged
one; as you already have been told, recreating a DB connection and query everytime a new character is entered in a TextBox is a design issue, it will make your application less responsive and annoying, from a user experience point of view.
You should also avoid constructing SQL queries by concatenating values obtained from users; this leaves your code opened to SQL injection attacks.
For example, if anyone enters the following text intextBox1
:
';DROP DATABASE ParamBills;--
然后你被破坏了。
问候。
then you're busted.
Regards.
你可以做一件事。
拿一个HiddenField
并在TextChanged
事件中存储TextBox
值。
下面的内容...
You can do one thing.
Take oneHiddenField
and store theTextBox
value in it inside theTextChanged
Event.
Something like below...
private void textBox1_TextChanged(object sender, EventArgs e)
{
if(String.IsNullOrEmpty(hdnField.Value))
{
hdnField.Value = textBox1.Text;
}
else
{
hdnField.Value = hdnField.Value + "," + textBox1.Text;
}
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=192.168.1.4;Initial Catalog=ParamBills;Persist Security Info=True;User ID=sa;Password=login";
conn.Open();
SqlCommand cmd = new SqlCommand("select Product_Name,Product_Code,Item_Name,Item_code,qty from Master_Stock_Register where Product_Name IN (@TextBoxValue)", conn);
command.Parameters.AddWithValue("@TextBoxValue", hdnField.Value);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill (dt);
dataGridView1.DataSource = dt;
// dataGridView1.DataBind();
conn.Close();
}