Asp.net DropDownList’e Çalışma Anında Eleman Ekleme
DropDownList ile ziyaretçilere sunduğumuz listelerde bazı elemanları eklemeyi unutmuş olabiliriz yada kullanıcının karşısına çıkan listeyi istediği gibi doldurması gereken durumlar olabilir bu gibi durumlarda DropDownList kontrolüne çalışma anında eleman ekleyerek bu sorunu çözebiliriz, Eklenecek eleman için iki değer lazım bunlardan biri text, diğeride value bilgisi, text tarayıcı tarafında value ise program tarafında kullanacığımız bilgi. çok fazla uzatmadan örneğimize geçelim , eleman ekleme için kullanacağımız komut “DropDownList1.Items.Add(new ListItem(TextBox1.Text,TextBox2.Text));”
<asp:Label ID="Label3" runat="server" Font-Size="Large" ForeColor="HotPink" Font-Bold="True" Font-Italic="True" >Eklenecek Bilgi</asp:Label> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <br /> <asp:Label ID="Label4" runat="server" Font-Size="Large" ForeColor="HotPink" Font-Bold="True" Font-Italic="True" >Eklenecek Değer</asp:Label> <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> <br /> <asp:Button ID="Button1" runat="server" Font-Bold="true" Text="Listeye Eleman Ekle" ForeColor="SeaGreen" onclick="Button1_Click" /> <br /> <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" Font-Size="Large" ForeColor="Blue" Font-Bold="true" Font-Italic="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"> <asp:ListItem Value="Adana"></asp:ListItem> <asp:ListItem Value="Adıyaman"></asp:ListItem> <asp:ListItem Value="Afyon"></asp:ListItem> <asp:ListItem Value="Ağrı"></asp:ListItem> <asp:ListItem Value="Amasya"></asp:ListItem> <asp:ListItem Value="Ankara"></asp:ListItem> </asp:DropDownList>
DropDownList1.Items.Add(new ListItem(TextBox1.Text,TextBox2.Text));