从数据库获取列值并使用文本框对其进行操作

时间:2013-12-17 13:58:28

标签: c# sql-server

我正在使用我的项目中的两个表单(Form1& Form2)

在Form1上,要求用户输入用户名(textboxUsername)&密码(textboxPassword)

当用户登录时,Form2会弹出作为他的帐户,在那里他可以看到他的ID,用户名,姓名,姓氏,生日和金钱列。

登录部分:

MessageBox.Show("Data verified!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.Hide();
                Form2 frm2 = new Form2("Welcome: " + textBoxUsername.Text, textBoxUsername.Text);
                frm2.ShowDialog();

现在在Form2 button1上,用户可以看到他的列:

public class Form2: Form
{
    private string currentUserName = string.Empty;
    public Form2(string welcome, string UserName)
    {
       label2.Text = welcome;
       currentUserName = UserName;
    }
}

private void button1_Click(object sender, EventArgs e)
{
    string constring = @"Data Source=V-K\;Initial Catalog=ATMKlientet;Integrated Security=True";
    SqlCommand cmdDataBase = new SqlCommand(" select * from Clients where Username=@uname", conDataBase);
            cmdDataBase.Parameters.AddWithValue("@uname", currentUserName);

    try
    {
        SqlDataAdapter sda = new SqlDataAdapter();
        sda.SelectCommand = cmdDataBase;
        dbdataset = new DataTable();
        sda.Fill(dbdataset);
        BindingSource bSource = new BindingSource();

        bSource.DataSource = dbdataset;
        dataGridView1.DataSource = bSource;
        sda.Update(dbdataset);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

现在,在Form2中,我想添加一个textBox,登录用户可以在其中键入数值。如果他的Money列是100,当他在textBox中输入50时,Money列应该在数据库中保持50。否则,如果列值为ex.100且用户撤销200,则应生成错误。每当用户在textBox中输入值时,就像减法或撤销一样。

1 个答案:

答案 0 :(得分:0)

使用textbox_keydownEvent

textBox1.KeyDown += textBox1_KeyDown;

代码内部的方法:

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar)) //it will only allow numeric keys
        {
            e.Handled = true; //it will handle every non-numeric key, and will only allow integers and control keys
        }
        else
               //write your code to what ever you want to do with database or gridview columns
    }