2017-03-06 36 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/ –