Yagya Sharma
Yagya Sharma

Reputation: 437

Handling empty databound dropdown list in ASP.Net

I have an asp.net page that has the following form fields:

  1. Dropdown 1. This drop down receives the data via SQL data source.
  2. Dropdown 2. Based on the selection of the drop down 1, this drop down queries to the database using SQL datasource and is populated.
  3. A panel control that is placed below drop down list 2 and it has a set of the controls.

My problem is there may be a situation when nothing is returned from the datasource of drop down 2, I want to show an Item "No Data found" in the dropdown list 2 and simultaneously hide the panel that is placed below dropdown 2.

Can someone please let me know how this situation can be handled.

Appreciate the help.

Thanks, Yagya

Upvotes: 0

Views: 764

Answers (1)

Waqar Janjua
Waqar Janjua

Reputation: 6123

Add the following code to your dropdownlist1 selected index change event.

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    // Run this code when your sql datasource 2 does not return record, you can also place an IfElse condition
    DataTable dt = new DataTable();
    dt.Columns.Add("ID");
    dt.Columns.Add("Value");
    DataRow row = dt.NewRow();
    row[0] = "-1";
    row[1] = "Data Not Found";
    dt.Rows.Add(row);
    DropDownList2.DataSource = dt;
    DropDownList2.DataTextField = "Value";
    DropDownList2.DataValueField = "ID";
    DropDownList2.DataBind();

}

Updated answer: ( Try this one ) You can also place it in your sqldatasource2 selecting event.

protected void SqlDataSource2_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
    if (e.Arguments.TotalRowCount == 0)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("ID");
        dt.Columns.Add("Value");
        DataRow row = dt.NewRow();
        row[0] = "-1";
        row[1] = "Data Not Found";
        dt.Rows.Add(row);
        DropDownList2.DataSource = dt;
        DropDownList2.DataTextField = "Value";
        DropDownList2.DataValueField = "ID";
        DropDownList2.DataBind();
    }
}

The above code will add a Item to your dropdownlist having Text = "Data Not Found"

Upvotes: 0

Related Questions