如果在另一个文本框中输入值,如何在一个文本框中检索值&反之亦然 [英] how to retrieve values into one textbox if entered into other textbox & viceversa
问题描述
先生您好,
我正在用C#在Windows窗体应用程序中创建.
我创建了三个标签的名字,中间名,姓氏.在这些标签的前面将有文本框&下面的一个按钮称为搜索"按钮.我创建了一个表,其中的字段称为名字,中间名,姓氏和名字.插入值.现在在输出窗口中,如果我输入名字& ;,点击搜索按钮,数据将被检索到其他文本框中,中间名,姓氏.
这是我的代码,我认为我们需要更改查询:
Hello sir,
I am creating in windows form appliacation in C#.
I created three labels first name,middle name,last name. Infront of those labels there will be textboxes & one button below called "Search" Button. I had created a table in which fields called first name,middle name,last & inserted values. Now in the output window ,if i give a firstname & hit a search button,the data as to be retrived into other textboxes-middle name,last name.
this my code,i think we need to change the query:
//search button below.
private void button1_Click(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=CBP\\SQLEXPRESS;Initial Catalog=ECG;Integrated Security=True");
con.Open();
com = new SqlCommand("select middle,last from Table2 where first= '"+ textBox1.Text.Trim()+"'",con);
rdr = com.ExecuteReader();
bool temp = false;
while (rdr.Read())
{
//textBox1.Text = rdr.GetString(0);
textBox1.Text = rdr[0].ToString().Trim();//ToString();// GetString(1);
textBox2.Text = rdr[1].ToString().Trim();
//textBox4.Text = rdr.GetString(3);
//textBox5.Text = rdr.GetString(4);
//textBox6.Text = rdr.GetString(5);
//textBox7.Text = rdr.GetString(6);
//textBox8.Text = rdr.GetString(7);
//textBox9.Text = rdr.GetString(8);
//textBox10.Text = rdr.GetString(9);
temp = true;
}
if (temp == false)
MessageBox.Show("not found");
con.Close();
con.Open();
ds = new DataSet();
da = new SqlDataAdapter("select * from Table2", con);
da.Fill(ds, "Table2");
con.Close();
}
如何实现此功能.
请帮我
谢谢
Pradeep CBZ
How to achieve this sir.
please do help me
Thanks
Pradeep CBZ
推荐答案
首先,最好使用参数化查询,而不是像这样串联字符串
First off, it is best to use a parameterised query rather than concatenating strings like this
com = new SqlCommand("SELECT middle, last FROM Table2 WHERE first = @firstName", con);
com.Parameters.AddWithValue(@firstName", textBox1.Text.Trim());
然后,您可以使用dr.HasRows而不是使用像这样的临时布尔变量:-
Then you can use dr.HasRows instead of using a temp bool variable like this:-
if(dr.HasRows)
{
while(dr.Read())
{
txtLast.Text = (string)dr[0];
txtMiddle.Text = (string)dr[1];
}
dr.Close();
}
else
{
MessageBox.Show("Not found !");
}
这篇关于如果在另一个文本框中输入值,如何在一个文本框中检索值&反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!