2014-01-16 73 views
1
private void Form1_Load(object sender, EventArgs e) 
     { 
     OleDbConnection con = new OleDbConnection(constr); 
     OleDbCommand cmd = new OleDbCommand("select project_name, ID from tb_project", con); 
     con.Open(); 

     OleDbDataReader DR = cmd.ExecuteReader(); 
     DataTable table = new DataTable(); 
     table.Load(DR); 
     combo_status.DataSource = table; 
     combo_status.DisplayMember = "project_name"; 
     combo_status.ValueMember = "ID"; 
     combo_status.Text = "Select Project Name"; 
    } 

private void btnSave_Click_Click(object sender, EventArgs e) 
    { 
     OleDbConnection con = new OleDbConnection(constr); 
     con.Open(); 
     OleDbCommand cmd = new OleDbCommand("Insert Into tb1(name) Values (@name)", con); 

     cmd.Parameters.AddWithValue("name", combo_status.SelectedValue); 

     cmd.ExecuteNonQuery(); 
     con.Close(); 
     MessageBox.Show("Inserted sucessfully"); 

    } 

選擇在第一類中,我有一個組合框,我從數據庫中獲取它的價值,我已經顯示「選擇項目名稱」在頁面加載在combobox.I要插入它的值只有當用戶從下拉菜單中選擇選項時,如果用戶沒有選擇任何選項,則不插入任何內容。ID越來越不插在C#.NET

現在的問題是,在下拉列表中的名字插入按鈕click.without沒有選擇任何選項。我希望如果用戶沒有從下拉選擇任何名稱值應該沒有插入。

任何人都可以幫助我..?

+0

因爲你的組合框的selectedIndex默認情況下等於0(-1,如果你的數據源爲空),因此,如果你不想插入任何東西到數據庫如果用戶沒有從組合框中選擇,你可以添加一個空行作爲組合框的第一個項目, –

+0

如何添加一個空行作爲組合框的第一個項目,你可以告訴我?? – user3181292

+0

看到我的回答下面 –

回答

1

假設ID列的該數據類型爲int:

private void Form1_Load(object sender, EventArgs e) 
    { 
    OleDbConnection con = new OleDbConnection(constr); 
    OleDbCommand cmd = new OleDbCommand("select project_name, ID from tb_project", con); 
    con.Open(); 

    OleDbDataReader DR = cmd.ExecuteReader(); 
    DataTable table = new DataTable(); 
    table.Load(DR); 

    //begin adding line 
    DataRow row = table.NewRow(); 
    row["project_name"] = "Select Project Name"; 
    row["ID"] = 0; 
    table.Rows.InsertAt(row, 0); 
    //end adding line 

    combo_status.DataSource = table; 
    combo_status.DisplayMember = "project_name"; 
    combo_status.ValueMember = "ID"; 
    combo_status.Text = "Select Project Name"; 
} 

private void btnSave_Click_Click(object sender, EventArgs e) 
{ 
    if(combo_status.SelectedValue == 0) 
    { 
     return; //do nothing if user didn't select anything in combobox, you can change this line of code with whatever process you want 
    } 

    OleDbConnection con = new OleDbConnection(constr); 
    con.Open(); 
    OleDbCommand cmd = new OleDbCommand("Insert Into tb1(name) Values (@name)", con); 

    cmd.Parameters.AddWithValue("name", combo_status.SelectedValue); 

    cmd.ExecuteNonQuery(); 
    con.Close(); 
    MessageBox.Show("Inserted sucessfully"); 

} 

希望這將幫助你

+0

是的,它的工作... thanxx很多.... :) – user3181292

+0

不客氣,玩編碼:) –