【发布时间】:2016-03-17 09:12:39
【问题描述】:
如何在每次点击保存按钮时自动增加 textBox1 中的值(即 ID)?我的问题是 textBox1 中的值只会在我每次运行 winform 时增加。
例如,我运行 winform 并且 ID 的最后一个值为 2,textbox1 将生成数字 3,在我单击保存按钮后它不会生成下一个数字,而是只会在我关闭时增加表单并重新运行它。请帮助..
在表单加载中
private void Form1_Load(object sender, EventArgs e)
{
int a;
String path1 = "Data Source=LOCALHOST; Initial Catalog= ss; username=root; password=''";
MySqlConnection con = new MySqlConnection(path1);
con.Open();
string query = "Select Max(ID) from inc";
MySqlCommand cmd = new MySqlCommand(query, con);
MySqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
string val = dr[0].ToString();
if (val == "")
{
textBox1.Text = "1";
}
else
{
a = Convert.ToInt32(dr[0].ToString());
a = a + 1;
textBox1.Text = a.ToString();
}
}
}
在保存按钮中
private void button1_Click(object sender, EventArgs e)
{
String path = "Data Source=LOCALHOST; Initial Catalog= ss; username=root; password=''";
MySqlConnection sqlconn = new MySqlConnection(path); //communicator //constructors
MySqlCommand sqlcomm = new MySqlCommand();
MySqlDataReader sqldr;
sqlconn.Open();
sqlcomm.Connection = sqlconn;
sqlcomm.CommandType = CommandType.Text;
sqlcomm.CommandText = "Select * from inc where ID=" + textBox1.Text + "";
sqldr = sqlcomm.ExecuteReader();
sqldr.Read();
if (sqldr.HasRows)
{
textBox3.Text = sqldr[0].ToString();
}
sqlconn.Close();
if (textBox1.Text == textBox3.Text)
{
MessageBox.Show("ID already exists!");
}
else
{
String path1 = "Data Source=LOCALHOST; Initial Catalog= ss; username=root; password=''";
MySqlConnection sqlconnn = new MySqlConnection(path1); //communicator //constructors
MySqlCommand sqlcommm = new MySqlCommand();
sqlconnn.Open();
sqlcommm.Connection = sqlconnn;
sqlcommm.CommandType = CommandType.Text;
sqlcommm.CommandText = "INSERT INTO inc (ID,Lastname) VALUES ("+ textBox1.Text +", '" + textBox2.Text + "')";
sqlcommm.ExecuteNonQuery();
sqlconnn.Close();
MessageBox.Show("RECORD SAVED!");
}
}
【问题讨论】:
-
改用数字上下。