Reputation: 73
I am trying to populate my combobox with names in my stored procedure.
public frmAddEdit(Book book, Author author)
{
_book = book;
_author = author;
_dataAccess = DataAccess.GetInstance;
_dataAccess.SetConnectionString(_dataAccess.GetServerConnectionString());
ComboFill();
InitializeComponent();
}
this is my load form
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;
}
my combobox
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataRowView view = comboBox1.SelectedItem as DataRowView;
string fullName = view["FullName"].ToString();
}
something i saw online and tried it.
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";
}
Upvotes: 1
Views: 5432
Reputation: 1
I had the same issue, I fixed it using SqlDataAdapter and passing it my stored procedure
public void PopulateDropdown()
{
// Check to see if connection is closed, to be safe, if closed then open
if (connection_db.State == ConnectionState.Closed)
connection_db.Open();
SqlDataAdapter sqlData = new SqlDataAdapter("StoredProcedureHere", connection_db);
// Must specify 'SelectCommand' when using get queries
sqlData.SelectCommand.CommandType = CommandType.StoredProcedure;
DataTable table = new DataTable();
// Store data in table
sqlData.Fill(table);
dropdownForNames.ValueMember = "player_id";
dropdownForNames.DisplayMember = "name";
dropdownForNames.DataSource = table;
// Close connection
connection_db.Close();
}
Upvotes: 0
Reputation: 499
//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";
Upvotes: 1
Reputation: 3531
the comboBox1.DataSource = _bool.FullName;
is wrong. It should be:
comboBox1.DataSource = _book;
Upvotes: 1