如何自动从数据库中检索数据 [英] how to automatic retrieve data from the database

查看:79
本文介绍了如何自动从数据库中检索数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的所有人,



我有一个自动填充文本框,我想从数据库中检索价值。



对于前。



我有一个名为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


这篇关于如何自动从数据库中检索数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆