如何自动从数据库中检索数据

编程入门 行业动态 更新时间:2024-10-27 18:34:01
本文介绍了如何自动从数据库中检索数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

亲爱的所有人, 我有一个自动填充文本框,我想从数据库中检索价值。 对于前。 我有一个名为customerName的文本框,第二个文本框名为address第三个文本框balance。 现在我想,当我输入customerName时,它会自动显示他的数据库中的地址和余额值。

解决方案

如果你检查keydown怎么办?如果键是回车键,则为事件 如果键是enter,则调用数据库以选择地址和余额,其中customerName是文本框中的值,然后只需设置地址和金额textbox是从数据库返回的值....

private void txtCustomerName_KeyDown(object sender,KeyEventArgs e) { if(e.KeyCode!= Keys.Enter)返回; 尝试 {使用(SqlConnection conn = new SqlConnection(yourconnectionstring)) { SqlCommand cmd = new SqlCommand(SELECT address, amount FROM Users WHERE Name = @Name,conn); cmd.Parameters.AddWithValue(@ Name,txtCustomerName.Text.Trim()); conn.Open(); SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); if(reader.Read()) { txtAddress.Text = reader [address]。ToString(); txtAmount.Text = reader [amount]。ToString(); } else MessageBox.Show(没有名字为+ txtCustomerName.Text.Trim()的客户); } } catch(异常异常) { MessageBox.Show(exception.ToString()); } }

解决问题 感谢Dave963

Dear All, I have a autocomplete text box and I want to retrieve value from the database . For ex. I have a text box named "customerName" second textbox named "address" third textbox "balance". Now I want, when I typed in the customerName then it will show automatically his address and balance value from the database.

解决方案

What if you check on the keydown event if the key is the enter key If the key is enter make a call to the database to select the address and balance where the customerName is the value in the textbox and then just set the address and amount textbox's to the values returned from the database....

private void txtCustomerName_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode != Keys.Enter) return; try { using (SqlConnection conn = new SqlConnection("yourconnectionstring")) { SqlCommand cmd = new SqlCommand("SELECT address, amount FROM Users WHERE Name = @Name", conn); cmd.Parameters.AddWithValue("@Name", txtCustomerName.Text.Trim()); conn.Open(); SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); if (reader.Read()) { txtAddress.Text = reader["address"].ToString(); txtAmount.Text = reader["amount"].ToString(); } else MessageBox.Show("No customers with the name " + txtCustomerName.Text.Trim()); } } catch (Exception exception) { MessageBox.Show(exception.ToString()); } }

Problem Solved thanks Dave963

更多推荐

如何自动从数据库中检索数据

本文发布于:2023-10-28 05:37:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1535685.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据库中   数据

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!