You cannot add Item like this in ArrayList
arr.add[builderSelectedItem.text , "Builder"];
Add does not accept two arguments.
But you can add like this.
arr.Add(new ListItem(this.ddlBuilders.SelectedItem.Value, "Builder"));
But if you keep this kind of data in ViewState then you will get this error.
Type 'System.Web.UI.WebControls.ListItem' in Assembly 'System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' is not marked as serializable
So you need to make use of Session for holding ArraList.
Or you can use Dictionary.
In the below code i have shown you how to add ArrayList and Dictionary in Session and ViewState respectively.
HTML
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="ddlBuilders" runat="server">
<asp:ListItem Text="Please Select" Value="Please Select" />
<asp:ListItem Text="Bulider1" Value="Bulider1" />
<asp:ListItem Text="Bulider2" Value="Bulider2" />
</asp:DropDownList>
<br />
<asp:DropDownList ID="ddlConsultants" runat="server">
<asp:ListItem Text="Please Select" Value="Please Select" />
<asp:ListItem Text="Consultant1" Value="Consultant1" />
<asp:ListItem Text="Consultant2" Value="Consultant2" />
</asp:DropDownList>
<asp:Button Text="Save" OnClick="Save" runat="server" />
<br />
<asp:Button Text="Bind GridView" OnClick="BindGridView" runat="server" />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Text" HeaderText="Text" />
<asp:BoundField DataField="Value" HeaderText="Value" />
</Columns>
</asp:GridView>
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Key" HeaderText="Key" />
<asp:BoundField DataField="Value" HeaderText="Value" />
</Columns>
</asp:GridView>
</div>
</form>
Namespace
using System.Collections;
C#
protected void Save(object sender, EventArgs e)
{
ArrayList arr = new ArrayList();
Dictionary<string, string> dictionay = new Dictionary<string, string>();
if (this.ddlBuilders.SelectedItem.Value != "Please Select")
{
arr.Add(new ListItem(this.ddlBuilders.SelectedItem.Value, "Builder"));
dictionay.Add(this.ddlBuilders.SelectedItem.Value, "Builder");
}
if (this.ddlConsultants.SelectedItem.Value != "Please Select")
{
arr.Add(new ListItem(this.ddlConsultants.SelectedItem.Value, "Consultant"));
dictionay.Add(this.ddlConsultants.SelectedItem.Value, "Consultant");
}
Session["SelectedValues"] = arr;
ViewState["Data"] = dictionay;
}
protected void BindGridView(object sender, EventArgs e)
{
Dictionary<string, string> dictionay = (Dictionary<string, string>)ViewState["Data"];
ArrayList arr = (ArrayList)Session["SelectedValues"];
this.GridView1.DataSource = arr;
this.GridView1.DataBind();
this.GridView2.DataSource = dictionay;
this.GridView2.DataBind();
}