我正在尝试获取列表框1和2的selectedindex,并基于在两个列表框中选择的值更新我的databasetable,但是找不到找到将selectedindex放入我的sql语句的方法。有什么建议么?
private void Form1_Load(object sender, EventArgs e)
{
String cs = "Database=something;User=-;Password=-";
MySqlConnection dbconn = new MySqlConnection(cs);
dbconn.Open();
DataSet ds = new DataSet();
MySqlDataAdapter adapter = new MySqlDataAdapter(
"select * from reservasjon WHERE Rom_nr IS NULL ", dbconn);
adapter.Fill(ds);
this.listBox1.DataSource = ds.Tables[0];
this.listBox1.DisplayMember = "Rnr";
}
private void button1_Click(object sender, EventArgs e)
{
String cs = "Database=something;User=-;Password=-";
MySqlConnection dbconn = new MySqlConnection(cs);
dbconn.Open();
DataSet ds2 = new DataSet();
MySqlDataAdapter adapter2 = new MySqlDataAdapter(
"select * from rom WHERE etasje = '1' AND opptatt='1'", dbconn);
adapter2.Fill(ds2);
this.listBox2.DataSource = ds2.Tables[0];
this.listBox2.DisplayMember = "Rom_nr";
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string value1 = listBox1.SelectedIndex.ToString();
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
string value2 = listBox2.SelectedIndex.ToString();
}
private void button4_Click(object sender, EventArgs e)
{
string value1 = listBox2.Text;
string value2 = listBox1.Text;
MySqlDataReader dr = null;
try
{
String cs = "Database=something;User=-;Password=-";
string selectStatement = "UPDATE reservasjon SET Rom_nr='102' WHERE Rnr='2';";
System.Data.DataTable dt = new System.Data.DataTable();
MySqlConnection dbconn = new MySqlConnection(cs);
dbconn.Open();
MySqlDataAdapter sqlDa = new MySqlDataAdapter();
sqlDa.SelectCommand = new MySqlCommand(selectStatement, dbconn);
MySqlCommandBuilder cb = new MySqlCommandBuilder(sqlDa);
sqlDa.Fill(dt);
dt.Rows[0]["Rnr"] = "";
sqlDa.UpdateCommand = cb.GetUpdateCommand();
sqlDa.Update(dt);
}
catch (Exception s)
{
Console.WriteLine(s.Message);
}
}
最佳答案
这应该可以解决问题:
private void button4_Click(object sender, EventArgs e)
{
string value1 = listBox2.Text;
string value2 = listBox1.Text;
MySqlDataReader dr = null;
try
{
String cs = "Database=something;User=-;Password=-";
string selectStatement = "UPDATE reservasjon SET Rom_nr='"+value2+"' WHERE Rnr='"value1+"';";
System.Data.DataTable dt = new System.Data.DataTable();
MySqlConnection dbconn = new MySqlConnection(cs);
dbconn.Open();
MySqlDataAdapter sqlDa = new MySqlDataAdapter();
sqlDa.SelectCommand = new MySqlCommand(selectStatement, dbconn);
MySqlCommandBuilder cb = new MySqlCommandBuilder(sqlDa);
sqlDa.Fill(dt);
dt.Rows[0]["Rnr"] = "";
sqlDa.UpdateCommand = cb.GetUpdateCommand();
sqlDa.Update(dt);
}
catch (Exception s)
{
Console.WriteLine(s.Message);
}
}
关于c# - C#如何获取selectedIndex并执行SQL查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43265413/