2017-03-06 65 views
0

我想在我的存儲過程中用名稱填充我的組合框。用存儲過程中的數據填充組合框

public frmAddEdit(Book book, Author author) 
    { 
     _book = book; 
     _author = author; 
     _dataAccess = DataAccess.GetInstance; 
     _dataAccess.SetConnectionString(_dataAccess.GetServerConnectionString()); 
     ComboFill(); 
     InitializeComponent(); 
    } 

這是我的負荷形式

public void AddEditBook_Load(object sender, EventArgs e) 
    { 

     txtTitle.Text = _book.Title; 
     //comboBox1.DataSource = _book.FullName; 
     //comboBox1.ValueMember = "AuthorId"; 
     //comboBox1.DisplayMember = "FullName"; 
     ComboFill(); 
     //txtAuthor.Text = _author.FullName; 
     //txtAdd.Text = book.Title; 
    } 

我的組合框

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     DataRowView view = comboBox1.SelectedItem as DataRowView; 
     string fullName = view["FullName"].ToString(); 


    } 

東西,我在網上看到試了一下。

  public void ComboFill() 
    { 
     DataRow dr; 
     DataTable dt = new DataTable(); 

     dr = dt.NewRow(); 
     // dr.ItemArray = new object[] { 0, "Select Author" }; 
     dt.Rows.InsertAt(dr, 0); 
     comboBox1.DataSource = _book.FullName; 
     comboBox1.ValueMember = "AuthorId"; 
     comboBox1.DisplayMember = "FullName"; 
    } 
+0

爲什麼你做複雜的時候,你可以在一個簡單的方法做到這一點? –

+0

輸入'System.Windows.Forms.ComboBox'作爲沒有名爲'ValueMember'或'DisplayMember'的屬性。 –

+1

那麼,你的問題是什麼?你有什麼錯誤?有什麼問題? – Pikoh

回答

1
//assume this that you have datatable filled from stored procedure 
//This is sample for populating your combo 
DataTable dt = new DataTable(); 
dt.Columns.Add("AuthorID", typeof(int)); 
dt.Columns.Add("FullName", typeof(string)); 

DataRow dr = null; 
for (int i = 0; i < 10; i++) 
{ 
    dr = dt.NewRow(); 
    dr[0] = i; 
    dr[1] = "ABC" + i + 2 * i; 

    dt.Rows.Add(dr); 
} 

comboBox1.DataSource = dt; // this will be populated from SP 
comboBox1.ValueMember = "AuthorID"; 
comboBox1.DisplayMember = "FullName"; 
+0

這部分不會帶來數據庫中的全名... – SMG

+0

DataRow dr = null; (int i = 0; i <10; i ++) dr = dt.NewRow(); dr [0] = i; dr [1] =「ABC」+ i + 2 * i; dt.Rows.Add(dr); } – SMG

+0

我希望它將數據中的四個作者名稱帶入組合框 – SMG

1

comboBox1.DataSource = _bool.FullName;是錯誤的。它應該是:

comboBox1.DataSource = _book; 
+0

我想知道在填充一個conbobox時只有一個項目是什麼,如果可能有多個元素,您應該檢查J. SMTBCJ15的回答http://stackoverflow.com/posts/42625890/edit – bradbury9

+0

是的,現在有數據在mu combobox中,但我想保存在我的數據庫中的全名顯示在組合框中 – SMG

+0

在SO上,人們只能幫助你整個代碼@SMG。你有幸運的是這個問題沒有被低估。如果你仍然無法從上面的答案瞭解比看看這個鏈接http://www.c-sharpcorner.com/UploadFile/009464/bind-combobox-in-window-application-using-C-Sharp/ –