我想獲取列表框1和2的selectedindex,並根據兩個列表框中選擇的值更新我的databasetable,但無法找到一種方法來獲取selectedindexes進入我的sql語句。有什麼建議麼?c#如何獲取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);
}
}
如果要在更新查詢中使用SelectedIndex的值,那麼您應該在創建並運行查詢的地方閱讀並使用它們。你不解釋應該如何使用這些值。順便說一句UPDATE,INSERT,DELETE查詢應該使用MySqlCommand和ExecuteNonQuery方法來執行。 – Steve
我對你的意思和想要完成的事情有點困惑。選定的索引只是一個指向所選索引位置的數字。如果沒有問題,可以在查詢中使用它,或者在您使用它的類中抓取它,或者在全局聲明value1。如果您想要選擇的項目的值,那麼您將使用選定的索引來獲取陣列中該位置的項目。使用string.format構建器來動態創建帶有變量的選擇查詢。 –