shahid khan shahid khan - 8 days ago 5
SQL Question

No data is showing in combobox

I am trying show some data from a database to a combobox based on another combobox selection with this code:

private void metroComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet dt = new DataSet();
try
{
DateTime startDate = Convert.ToDateTime(metroLabel8.Text);
DateTime endDate = Convert.ToDateTime(metroLabel9.Text);
// Make sql readable
string sql =
@"Select [LedId],[LedName] from [Ledger] where Date >= @prmStartDate and Date <= @prmEndDate";

// wrap IDisposable (SqlCommand) into using
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add("@prmStartDate", SqlDbType.DateTime).Value = startDate;
cmd.Parameters.Add("@prmEndDate", SqlDbType.DateTime).Value = endDate;
con.Close();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
VoucherLedgerName_combo.DisplayMember = "LedName";
VoucherLedgerName_combo.ValueMember = "LedId";
VoucherLedgerName_combo.DataSource = dt.Tables["Ledger"];
}
}
catch(Exception exe)
{
MessageBox.Show(exe.Message);
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}


But i am getting nothing in the second combobox, and I am sure that there is data in the database table Ledger. Can any one please help me to find the issue?

Answer

change your SQL statement as below(Date is reserved keyword)

string sql = 
         @"Select [LedId],[LedName] from [Ledger] where [Date] >= @prmStartDate and [Date] <= @prmEndDate";

You need to give table name when you fill dataset since you are using the name when you set data source

da.Fill(dt, "Ledger");

or set the data source as below

VoucherLedgerName_combo.DataSource = dt.Tables[0];