CasCading DropDownList using Array in Asp.net

CasCading DropDownList using Array in Asp.net

Sometimes we need to do fill dropdownlist using Array(2 Dimensional and 3 Dimensional) For Static Value in Asp.net

Explanation given below:

Design Page:

<div>
<asp:DropDownList ID=”ddlCountry” runat=”server” AutoPostBack=”True”
onselectedindexchanged=”ddlCountry_SelectedIndexChanged”>
</asp:DropDownList>
<asp:DropDownList ID=”ddlState” runat=”server”>
</asp:DropDownList>
</div>

Code Page:

protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindCountry();
}
}
public void BindCountry()
{
string[,] Country = { { “India”, “1” }, { “US”, “2” } };
int rows = Country.GetUpperBound(0);
int columns = Country.GetUpperBound(1);

for (int currentRow = 0; currentRow <= rows; currentRow++)
{
ListItem li = new ListItem();
for (int currentColumn = 0; currentColumn <= columns; currentColumn++)
{
if (currentColumn == 0)
{
li.Text = Country[currentRow, currentColumn];
}
else
{
li.Value = Country[currentRow, currentColumn];
}
}
ddlCountry.Items.Add(li);
}

}
public void BindState(int id)
{
string[, ,] State = { {{ “UP”, “1”, “1” }},
{ {“Patna”, “2”, “1” }},
{{ “Delhi”, “3”, “1” }},
{ {“Haryana”, “4”, “1” }},
{ {“AK – Alaska”, “14”, “2” }},
{ {“AL – Alabama”, “15”, “2” }},
{ {“AR – Arkansas”, “16”, “2” }} ,
{ {“AZ – Arizona”, “17”, “2” } },
{ {“CA – California”, “18”, “2” }},
{ {“CO – Colorado”, “19”, “2” }},
{ {“CT – Connecticut”, “20”, “2” }},
};
DataTable objDat = new DataTable();
objDat.Columns.Add(“StateName”, typeof(string));
objDat.Columns.Add(“SId”, typeof(string));
objDat.Columns.Add(“CId”, typeof(string));
for (int i = 0; i < State.Length/3; i++)
{

DataRow dr = objDat.NewRow();
dr[“StateName”]= State[i,0,0];
dr[“SId”] = State[i, 0, 1];
dr[“CId”] = State[i, 0, 2];
objDat.Rows.Add(dr);

}

DataRow[] drData = objDat.Select(“CId=” + id);
DataTable dt1 = drData.CopyToDataTable();
ddlState.DataSource = dt1;
ddlState.DataTextField = “StateName”;
ddlState.DataValueField = “SId”;
ddlState.DataBind();
}
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{

if (Convert.ToInt32(ddlCountry.SelectedValue) > 0)
{
BindState(Convert.ToInt32(ddlCountry.SelectedValue));
}
}

cas

 

 

 

 

 

 

 

Download Code: Array

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply