asp.net listview dropdownlist


Here is how to bind an asp.net listview dropdown list:

1) Example 1:

<ItemTemplate>

<tr>

<td

<asp:DropDownList ID="ddlProducts" runat="server"

DataTextField="Product_name"

DataValueField="Product_id"

OnInit="ddlProducts_Init"/>

</td>

</ItemTemplate>

The value of the OnInit property must match the name of the event handler method in the code behind:

protected void ddlProducts_Init(object sender, EventArgs e)

{

DropDownList ddlProducts = (DropDownList)sender;

DataTable dtProductsList = new DataTable();

try

{

dtProductsList = Data.GetProducts();

ddlProducts.DataSource = dtProductsList ;

ddlProducts.DataBind();

}

catch (Exception ex)

{

Response.Redirect("~/Pages/Error.aspx");

}

}

Here is the Data.GetProducts method:

public DataTable GetProducts()
{
    DataTable dtRetrieveProducts = new DataTable();
    try
    {
        dtRetrieveProducts = Data.GetProductsList();
    }
    catch (Exception ex)
    {
       
    }

    DataTable dtProducts = new DataTable();
    dtProducts.Columns.Add(new DataColumn("Product_id", Type.GetType("System.String")));
    dtProducts.Columns.Add(new DataColumn("Product_name", Type.GetType("System.String")));
    DataRow drinitRow = dtProducts.NewRow();
    drinitRow["Product_id"] = -1;
    drinitRow["Product_name"] = "Select a product";
    dtProducts.Rows.Add(drinitRow);
    if (dtRetrieveProducts.Rows.Count > 0)
    {
        for (int i = 0; i < dtRetrieveProducts.Rows.Count; i++)
        {
            DataRow drRow = dtProducts.NewRow();
            drRow["Product_id"] = dtRetrieveProducts.Rows[i]["Product_id"];
            drRow["Product_name"] = dtRetrieveProducts.Rows[i]["Product_id"] + "  " + dtRetrieveProducts.Rows[i]["Product_name"];              

            dtProducts.Rows.Add(drRow);
        }
    }

    return dtProducts;
}

2) Example 2:

<ItemTemplate>

<tr>

<td

<asp:DropDownList ID="ddlMaritalStatus" runat="server"

OnInit="ddlMaritalStatus_Init"/>

</td>

</ItemTemplate>

The value of the OnInit property must match the name of the event handler method in the code behind:

protected void ddlMaritalStatus_Init(object sender, EventArgs e)

{

DropDownList ddlMaritalStatus= (DropDownList)sender;

ListItem ddlListItem1 = new ListItem();

ddlListItem1.Value = "M";

ddlListItem1.Text = "Married";

ddlMaritalStatus.Items.Add(ddlListItem1);

ListItem ddlListItem2 = new ListItem();

ddlListItem2.Value = "S";

ddlListItem2.Text = "Single";

ddlPaymentType.Items.Add(ddlListItem2);

}

No comments:

Post a Comment