Why is my DropDownList not working? - c#

I would like to display a DropdownList but it isn't working yet.
This is my asp.net code:
<asp:Panel ID="pnlChannel" runat="server">
<asp:SqlDataSource ID="sdsChannel" runat="server"></asp:SqlDataSource>
<asp:DropDownList ID="ddlChannel" runat="server">
<asp:ListItem id="limDefault" runat="server"></asp:ListItem>
</asp:DropDownList>
</asp:Panel>
And then this is my codebehind:
public Panel GetDropDownList()
{
// Create drop down list and data source
Panel pnlChannel = new Panel();
DropDownList ddlChannel = new DropDownList();
ListItem limDefault = new ListItem();
SqlDataSource sdsChannel = new SqlDataSource();
// Configure data source
sdsChannel.ConnectionString = ConfigurationManager.ConnectionStrings["CR_SQL"].ConnectionString;
sdsChannel.SelectCommand = "SELECT * FROM TABLE";
sdsChannel.ID = "sdsChannel";
// Configure drop down list
ddlChannel.DataTextField = "Channel";
ddlChannel.DataValueField = "Channel";
ddlChannel.AppendDataBoundItems = true;
ddlChannel.DataSourceID = "sdsChannel";
// Configure default list item
limDefault.Selected = true;
limDefault.Text = "All";
limDefault.Value = "-1";
// Add controls to static panel in footer
ddlChannel.Items.Add(limDefault);
pnlChannel.Controls.Add(ddlChannel);
pnlChannel.Controls.Add(sdsChannel);
return pnlChannel;
}
Did I miss something?
So I think the ListItem isn't working, because there is a DropDownList but I can't see any list to drop down.

You have not set Text property of ListItem. Also remove code from .cs file for creating controls because this will duplicate the controls.
<asp:DropDownList ID="ddlChannel" runat="server">
<asp:ListItem id="limDefault" runat="server" Text="SomeText" Value="SomeValue"></asp:ListItem>
</asp:DropDownList>

Related

Using dropdown names as variable in asp.net

I wants to use dropdown names as variable in asp.net webpage.
We have 10 dropdownlist with id- ddl1,ddl2,....ddl10.
What my requirement is that i need to show and hide from the code behind file
<div id ="divContainer" class="field" runat="server">
<asp:Label ID="lblmsg1" runat="server" Text="" CssClass="fieldtxt">
<asp:DropDownList ID="DropDownList1" runat="server" CssClass="fieldtxtbox1" OnSelectedIndexChanged="ddlCommand_SelectedIndexChanged">
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server" CssClass="fieldtxtbox1" OnSelectedIndexChanged="ddlCommand_SelectedIndexChanged">
</asp:DropDownList>
<asp:DropDownList ID="DropDownList3" runat="server" CssClass="fieldtxtbox1" OnSelectedIndexChanged="ddlCommand_SelectedIndexChanged">
</asp:DropDownList>
<asp:DropDownList ID="DropDownList4" runat="server" CssClass="fieldtxtbox1" OnSelectedIndexChanged="ddlCommand_SelectedIndexChanged">
</asp:DropDownList>
//like this 10 different DropDownList
</div>
i have certain loop for doing that.
i need something like this...
ddl[i].Visible = true;
when i tried this got error like
'System.Web.UI.WebControls.DropDownList' is a 'type' but is used like a 'variable'
Please help
This should do the trick
DropDownList ddls = null;
for (int i = 1; i <= 10; i++) {
ddls = (DropDownList)this.FindControl("DropDownList" + i);
if (ddls != null) {
ddls.Visible = true;
}
}
The controls should be immediate children of the page. If these are embedded in other server control such as FormView, GridView etc or on Master page, then you must use that control or master in conjunction with FindControl
Why not using javascript?
//save the div in a var
//check the name of the div in the generated html, it might be different from the name you have in asp.net
var divContainer = document.getElementById("divContainer");
//get all ddl contsols by Tag (tag for ddl is select)
var ddls = divContainer.GetElementByTag("select");
//iterate through the found select controls from the div and set them to visible
for (var i = 0, len = ddls.length; i < len; ++i)
{
ddls[i].style.display='block';
}

How to add disable field in ASP.NET dropdownList

I need to add the diable field "Select..." in dropdownList. The data is bind along with datasourse in code behind. I am have tried to add disable field but I can see any result.
Code Behind
AvailableRolesList = RoleDefinationRelay.GetAllRoles(null);
ddlRolesList.DataSource = AvailableRolesList;
ddlRolesList.DataTextField = "Title";
ddlRolesList.DataValueField = "RoleID";
ddlRolesList.DataBind();
DropdownList
<asp:DropDownList ID="ddlRolesList" runat="server">
<asp:ListItem Text="SelectRole" Enabled="false" Selected="True">Select Role</asp:ListItem>
</asp:DropDownList>
enter code here
You need to add Select item after binding dropdownlist in code behind.
AvailableRolesList = RoleDefinationRelay.GetAllRoles(null);
ddlRolesList.DataSource = AvailableRolesList;
ddlRolesList.DataTextField = "Title";
ddlRolesList.DataValueField = "RoleID";
ddlRolesList.DataBind();
ddlRolesList.Items.Insert(0, "Select Role");
here is my answer
ddlRolesList.Items.Insert(0, new ListItem("Select Role","NA"));

My ASP.NET DropDownList is not working

I would like to make a DropDownList inside a panel. This is my code from the codebehind file. But if I execute it, it always says: "in DropdownList it is not allowed to make multiple selections." Do I have to do something with the autopostback? So the error comes when I want to select something else than than "All".
DropDownList1.DataTextField = "Kanal";
DropDownList1.DataValueField = "Kanal";
DropDownList1.AppendDataBoundItems = true;
ListItem limDefault = new ListItem();
limDefault.Selected = true;
limDefault.Text = "All";
limDefault.Value = "-1";
DropDownList1.Items.Add(limDefault);
Then this is my ASP.NET code:
<asp:Panel ID="Panel1" runat="server">
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:CR_SQL %>" SelectCommand="Select * from table" >
</asp:SqlDataSource>
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1" AutoPostBack="True">
</asp:DropDownList>
</asp:Panel>
I guess you execute the first snippet on every postback which adds the default item every time. Do that only at the first time the page loads, therefore use Page.IsPostBack to check that:
if(!IsPostBack)
{
ListItem limDefault = new ListItem();
limDefault.Selected = true;
limDefault.Text = "All";
limDefault.Value = "-1";
DropDownList1.Items.Add(limDefault);
}

How to keep "select" as item[0] for drop down list

I have a drop down list in UpdatePanel_2, it gets populated when Button_1 is clicked in UpdatePanel_1,
when DropDownList is populated, it removes my "Select" item not sure why,
My Drop down list markup is,
<asp:DropDownList id="drop1" runat="server" >
<asp:ListItem Text=" Select " />
</asp:DropDownList>
This is how I am populating it,
using (SqlDataSource sqlds = new SqlDataSource(ConnectionString(), SelectCommand()))
{
drop1.DataSource = sqlds;
drop1.DataTextField = "UserName";
drop1.DataBind();
}
you need to add AppendDataBoundItems="true" to your DropDownList
but if you are populate DropDownList again and again you can do as below
<asp:DropDownList id="drop1" runat="server" ondatabound="drop1_DataBound" >
</asp:DropDownList>
Then in your code behind:
protected void drop1_DataBound(object sender, EventArgs e)
{
drop1.Items.Insert(0, new ListItem(" Select ", ""));
}
Or even below will work
<asp:DropDownList id="drop1" runat="server" >
</asp:DropDownList>
Then in your code behind:
using (SqlDataSource sqlds = new SqlDataSource(ConnectionString(), SelectCommand()))
{
drop1.DataSource = sqlds;
drop1.DataTextField = "UserName";
drop1.DataBind();// insert after DataBind
drop1.Items.Insert(0, new ListItem(" Select ", ""));
}

SelectedValue which is invalid because it does not exist in the list of items

This is the error I get:
ddlRankEdit' has a SelectedValue which is invalid because it does not
exist in the list of items. Parameter name: value
I have a form wiht several dropdownlists that are nested in a panel that is by default set to invisible. When a user selects a record from a separate list box the selected index changed event sets the panel to visible and makes a data call. That's when the error happens. See the code below, I added XXX where it stalls.
<asp:DropDownList runat="server" ID="ddlRankEdit" CssClass="txtfield" DataSourceID="ODCRanks"
DataTextField="Rank" DataValueField="ID" AppendDataBoundItems="True">
<asp:ListItem Text="--- Select a Rank ---" Value="-1" />
</asp:DropDownList>
<asp:ObjectDataSource ID="ODCRanks" runat="server"
OldValuesParameterFormatString="original_{0}" SelectMethod="GetRanks"
TypeName="RanksTableAdapters.RankTableAdapter"></asp:ObjectDataSource>
protected void lboxManageMembers_SelectedIndexChanged(object sender, EventArgs e)
{
pnlReviewMemberDetails.Visible = false;
pnlUnlockUserAccount.Visible = false;
pnlAdmins.Visible = false;
pnlCreateAdmins.Visible = false;
lblNote.Visible = false;
pnlManageMenbers.Visible = true;
MembershipUser user = Membership.GetUser();
DataSetTableAdapters.MemberInfoTableAdapter da = new DataSetTableAdapters.MemberInfoTableAdapter();
Guid _memberId = Guid.Empty;
_memberId = new Guid(lbxManageMembers.SelectedValue);
DataSet.MemberInfoDataTable dt = da.GetMember(_memberId);
if (dt.Rows.Count == 1)
{
DataSet.MemberInfoRow mr = dt[0];
XXX ddlRankEdit.SelectedValue = Convert.ToString(mr.rankid);
XXX ddlPatrolEdit.SelectedValue = Convert.ToString(mr.patrolid);
XXX ddlPositionEdit.SelectedValue = Convert.ToString(mr.bsaposid);
txtFirstNameEdit.Text = mr.firstname;
txtLastNameEdit.Text = mr.lastname;
txtEmailEdit.Text = user.Email;
txtAddressEdit.Text = mr.address;
txtPhoneEdit.Text = mr.phone;
txtCellPhoneEdit.Text = mr.altphone;
txtAltEmailEdit.Text = mr.altemail;
txtMotherFirstNameEdit.Text = mr.parentfn;
txtMotherLastNameEdit.Text = mr.parentln;
txtMotherWorkPhoneEdit.Text = mr.parentworkphone;
txtMotheHomePhoneEdit.Text = mr.parentworkphone;
txtMotherCellkPhoneEdit.Text = mr.parentscellphone;
txtMotherTwitterEdit.Text = mr.parenttwitter;
txtMotherEmailEdit.Text = mr.parentemail;
txtMotherAltEmailEdit.Text = mr.parentemailalt;
txtFatherFirstNameEdit.Text = mr.parent2fn;
txtFatherLastNameEdit.Text = mr.parent2ln;
txtFatherWorkPhoneEdit.Text = mr.parent2workphone;
txtFatherHomePhoneEdit.Text = mr.parent2workphone;
txtFatherCellPhoneEdit.Text = mr.parent2cellphone;
txtFatherTwitterEdit.Text = mr.parent2twitter;
txtFatherEmailEdit.Text = mr.parent2email;
txtFatherAltEmailEdit.Text = mr.parent2emailalt;
}
}
The error message is telling you exactly what is happening: the value, for example stored in mr.rankid, is not present in the dropdownlist.
You need to figure out whether or not the dropdownlist contains the correct value or the value you are trying to assign does not exist in the list of available values.
Update
Since it is the visibility of the containing panel that seems to be causing the problems, it would be better to hide the panel using CSS than setting the Visible property to false, which will prevent it from rendering to the page.
This can be done with code similar to the following in the code-behind:
Panel1.Style.Add(HtmlTextWriterStyle.Visibility, "Hidden");
Panel1.Style.Add(HtmlTextWriterStyle.Display, "None");
modify your code like this:
if (dataTable1.Rows[0]["columnName"].ToString() != "" && dataTable1.Rows[0]["columnName"] != null)
DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByValue(dataTable1.Rows[0]["columnName"].ToString()));
you can use this codes for use dropdownlist in editemplate when you dont need to use a datasource :
<asp:TemplateField HeaderText="state" SortExpression="state">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList4" runat="server" Style="position: relative" AppendDataBoundItems="true" SelectedValue='<%# Bind("state") %>' >
<asp:ListItem Value="approved">approved</asp:ListItem>
<asp:ListItem Value="notapproved">notapproved</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("state") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>

Categories