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);
}
Related
I'm trying to create a filter through DropDownList.
They are using Datasources.
The problem is - these sources don't include empty value and filter always works. Of course I don't need it. I tryied to add ListItem right incide of DropDownList but it didn't help.
Here is one of my DropDownList.
<asp:DropDownList ID="ddl" runat="server" DataSourceID="sds"
DataTextField="name" DataValueField="id">
</asp:DropDownList>
<asp:SqlDataSource ID="sds" runat="server"
ConnectionString="<%$ ConnectionStrings:conStr %>"
OnInit="sds_Init"></asp:SqlDataSource>>
Will be grateful for your help!
You can do it in code behind:
ddl.Items.Add(new ListItem("--Select--", "-1"));
Or:
ddl.Items.Insert(0, new ListItem("--Select--", "-1"));
Or on your .aspx:
<asp:DropDownList ID="ddl" runat="server" DataSourceID="sds"
DataTextField="name" DataValueField="id">
<asp:ListItem Text="--Select--" Value ="-1"></asp:ListItem>
</asp:DropDownList>
Or potentially in your SQL:
SELECT "--Select--" AS [name], -1 as [id]
UNION
SELECT ...
I am doing the same thing this way, Try this once
AffiliatesDomain affiliateDomain = new AffiliatesDomain();
List<usp_selectAffiliatesForMasterResult> objListAffiliate = new List<usp_selectAffiliatesForMasterResult>();
objListAffiliate = affiliateDomain.SelctAffiliatesForMasterAgent();
ddlAffiliate.DataSource = objListAffiliate;
ddlAffiliate.DataTextField = "PartnerAffiliatCodeName";
ddlAffiliate.DataValueField = "AffiliateId";
ddlAffiliate.DataBind();
ddlAffiliate.Items.Insert(0, new ListItem("--Select--", "0"));
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>
I'm trying to change the Select Command my DataSource uses using a dropdownlist. When the page loads it sets the select command depending on the selected index. When I change the dropdownlist the page refreshes but the data doesn't! Where am I going wrong?
.aspx file
<asp:DropDownList ID="filmFilter" runat="server" OnSelectedIndexChanged="filmFilter_SelectedIndexChanged" AutoPostBack="True">
<asp:ListItem Value="">Filter</asp:ListItem>
<asp:ListItem Value="priceASC">Price: Low-High</asp:ListItem>
<asp:ListItem Value="priceDSC">Price: High-Low</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionStringFilms %>"></asp:SqlDataSource>
<asp:ListView ID="ListView1" runat="server" DataKeyNames="filmID" DataSourceID="SqlDataSource1" OnSelectedIndexChanged="ListView1_SelectedIndexChanged">
<ItemTemplate>
...
</ItemTemplate>
<LayoutTemplate>
...
</LayoutTemplate>
</asp:ListView>
code-behind - page load:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (filmFilter.SelectedIndex == 0)
{
SqlDataSource1.SelectCommand = "SELECT * FROM [films]";
}
if (filmFilter.SelectedIndex == 1)
{
SqlDataSource1.SelectCommand = "SELECT * FROM [films] ORDER BY [filmPrice]";
}
if (filmFilter.SelectedIndex == 2)
{
SqlDataSource1.SelectCommand = "SELECT * FROM [films] ORDER BY [filmPrice] DESC";
}
}
}
Thanks!
You've got it so your datasource is set on the page_load which is fine but you've wrapped it in
if (!IsPostBack)
{
Which means your code to change the datasource will only happen when you are not in postback (when you change the value of the dropdown you will be in a postback)
Have a read through
http://msdn.microsoft.com/en-us/library/ms178472(v=vs.100).aspx
It will help with your understanding
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>
I have a Formview that gets populated with SQL data when a dropdown is selected, but when I click edit, it wants to edit the first item on the dropdown list, because technically it still thinks its on the first page. I want the paging to be linked to the drop down but I'm not exactly sure how to accomplish this. I have a many fields so I won't post the full Formview but here's the key parts.
Formview Item Template:
<ItemTemplate>
<table id="FormTable">
<tr><th>
<asp:DropDownList ID="ProjectNameDropDown" runat="server" AutoPostBack="true"
DataSourceID="SqlDataSource1"
DataValueField="Project_Name" name="Text" OnSelectedIndexChanged="ProjectSelect" AppendDataBoundItems="true">
<asp:ListItem Text="Select a Project" />
</asp:DropDownList>
<asp:Panel ID="Panel1" runat="server" Visible="false">
</th>
<th>
<asp:Button ID="EditButton" runat="server" CausesValidation="False"
CommandName="Edit" Text="Edit" />
<asp:Button ID="DeleteButton" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete" />
<asp:Button ID="NewButton" runat="server" CausesValidation="False"
CommandName="New" Text="New" />
</th></tr>
<tr><th>
Business Category:
</th><td>
<asp:Label ID="BusinessCategoryLabel" runat="server"
Text='<%# Bind("Business_Category") %>'
/>
</td></tr>
<tr><th>
Project Description:
</th><td>
<asp:TextBox ID="ProjectDescriptionLabel" runat="server" ReadOnly="true"
Text='<%# Bind("Project_Description") %>' TextMode="MultiLine" Rows="5" />
</td></tr>
<tr><th>
Operations Owner:
</th><td>
<asp:Label ID="OwnerLabel" runat="server"
Text='<%# Bind("Operations_Owner") %>' />
</td></tr>
Code Behind:
protected void ProjectSelect(object sender, EventArgs e)
{
DropDownList ProjectNameDropDown = (DropDownList)FormView1.FindControl("ProjectNameDropDown");
Panel Panel1 = (Panel)FormView1.FindControl("Panel1");
Label BusinessCategoryLabel = (Label)FormView1.FindControl("BusinessCategoryLabel");
TextBox ProjectDescriptionLabel = (TextBox)FormView1.FindControl("ProjectDescriptionLabel");
Label OwnerLabel = (Label)FormView1.FindControl("OwnerLabel");
Label StakeholderLabel = (Label)FormView1.FindControl("StakeholderLabel");
Label ReqOrgLabel = (Label)FormView1.FindControl("ReqOrgLabel");
Label PriorityLabel = (Label)FormView1.FindControl("PriorityLabel");
Label DateInitiatedLabel = (Label)FormView1.FindControl("DateInitiatedLabel");
Label ReqCompletionDateLabel = (Label)FormView1.FindControl("ReqCompletionDateLabel");
Label ProjectLOELabel = (Label)FormView1.FindControl("ProjectLOELabel");
Label OELabel = (Label)FormView1.FindControl("OELabel");
Label PELabel = (Label)FormView1.FindControl("PELabel");
Label EMLabel = (Label)FormView1.FindControl("EMLabel");
Label PARCHLabel = (Label)FormView1.FindControl("PARCHLabel");
Label WindowsLabel = (Label)FormView1.FindControl("WindowsLabel");
Label StorageLabel = (Label)FormView1.FindControl("StorageLabel");
Label NetworkLabel = (Label)FormView1.FindControl("NetworkLabel");
Label Unix2Label = (Label)FormView1.FindControl("Unix2Label");
Label TSGLabel = (Label)FormView1.FindControl("TSGLabel");
Label SANDLabel = (Label)FormView1.FindControl("SANDLabel");
Label MOPSLabel = (Label)FormView1.FindControl("MOPSLabel");
Label ACSROpsLabel = (Label)FormView1.FindControl("ACSROpsLabel");
Label IMOpsLabel = (Label)FormView1.FindControl("IMOpsLabel");
Label OSCOpsLabel = (Label)FormView1.FindControl("OSCOpsLabel");
Label FinancialSvcsLabel = (Label)FormView1.FindControl("FinancialSvcsLabel");
Label VantageLabel = (Label)FormView1.FindControl("VantageLabel");
Label VoiceSysOpsLabel = (Label)FormView1.FindControl("VoiceSysOpsLabel");
Label VoiceAppOpsLabel = (Label)FormView1.FindControl("VoiceAppOpsLabel");
Label ACPxOpsLabel = (Label)FormView1.FindControl("ACPxOpsLabel");
Label WFXOpsLabel = (Label)FormView1.FindControl("WFXOpsLabel");
Label WebOpsLabel = (Label)FormView1.FindControl("WebOpsLabel");
Label DBALabel = (Label)FormView1.FindControl("DBALabel");
Label CapacityPlanningLabel = (Label)FormView1.FindControl("CapacityPlanningLabel");
Label BCPLabel = (Label)FormView1.FindControl("BCPLabel");
Label DataCenterLabel = (Label)FormView1.FindControl("DataCenterLabel");
Label GoldsmithLabel = (Label)FormView1.FindControl("GoldsmithLabel");
Label AmericasITOpsLabel = (Label)FormView1.FindControl("AmericasITOpsLabel");
Label APACITOpsLabel = (Label)FormView1.FindControl("APACITOpsLabel");
Label EMEAITOpsLabel = (Label)FormView1.FindControl("EMEAITOpsLabel");
Panel1.Visible = true;
if (ProjectNameDropDown.Items.FindByText("Select a Project").Selected != true)
{
string myConnectionString = #"Data Source=odcsgwinsql11.devcsg.com\ss2008;Initial Catalog=hulc01;Integrated Security=True";
SqlConnection myConnection = new SqlConnection(myConnectionString);
string MySelectQuery = "SELECT * FROM Common WHERE Project_Name = '" + ProjectNameDropDown.SelectedValue + "'";
using (SqlCommand cmd = new SqlCommand(MySelectQuery))
{
cmd.Connection = myConnection;
myConnection.Open();
SqlDataAdapter Adapter1 = new SqlDataAdapter(cmd);
DataSet dset = new DataSet();
Adapter1.Fill(dset);
BusinessCategoryLabel.Text = dset.Tables[0].Rows[0]["Business_Category"].ToString();
ProjectDescriptionLabel.Text = dset.Tables[0].Rows[0]["Project_Description"].ToString();
OwnerLabel.Text = dset.Tables[0].Rows[0]["Operations_Owner"].ToString();
StakeholderLabel.Text = dset.Tables[0].Rows[0]["NonOps_Key_Stakeholder"].ToString();
ReqOrgLabel.Text = dset.Tables[0].Rows[0]["Requesting_Organization"].ToString();
PriorityLabel.Text = dset.Tables[0].Rows[0]["Priority"].ToString();
DateInitiatedLabel.Text = dset.Tables[0].Rows[0]["Date_Initiated"].ToString();
ReqCompletionDateLabel.Text = dset.Tables[0].Rows[0]["Required_Completion_Date"].ToString();
ProjectLOELabel.Text = dset.Tables[0].Rows[0]["Project_LOE"].ToString();
OELabel.Text = dset.Tables[0].Rows[0]["OE"].ToString();
PELabel.Text = dset.Tables[0].Rows[0]["PE"].ToString();
EMLabel.Text = dset.Tables[0].Rows[0]["EM"].ToString();
PARCHLabel.Text = dset.Tables[0].Rows[0]["PARCH"].ToString();
WindowsLabel.Text = dset.Tables[0].Rows[0]["Windows"].ToString();
StorageLabel.Text = dset.Tables[0].Rows[0]["Storage"].ToString();
NetworkLabel.Text = dset.Tables[0].Rows[0]["Network"].ToString();
Unix2Label.Text = dset.Tables[0].Rows[0]["UNIX2"].ToString();
TSGLabel.Text = dset.Tables[0].Rows[0]["TSG"].ToString();
SANDLabel.Text = dset.Tables[0].Rows[0]["SAND"].ToString();
MOPSLabel.Text = dset.Tables[0].Rows[0]["MOPS"].ToString();
ACSROpsLabel.Text = dset.Tables[0].Rows[0]["ACSR_Ops"].ToString();
IMOpsLabel.Text = dset.Tables[0].Rows[0]["IM_Ops"].ToString();
OSCOpsLabel.Text = dset.Tables[0].Rows[0]["OSC_Ops"].ToString();
FinancialSvcsLabel.Text = dset.Tables[0].Rows[0]["Financial_Svcs"].ToString();
VantageLabel.Text = dset.Tables[0].Rows[0]["Vantage"].ToString();
VoiceAppOpsLabel.Text = dset.Tables[0].Rows[0]["Voice_Sys_Ops"].ToString();
VoiceSysOpsLabel.Text = dset.Tables[0].Rows[0]["Voice_App_Ops"].ToString();
ACPxOpsLabel.Text = dset.Tables[0].Rows[0]["ACPX_Ops"].ToString();
WFXOpsLabel.Text = dset.Tables[0].Rows[0]["WFX_Ops"].ToString();
WebOpsLabel.Text = dset.Tables[0].Rows[0]["Web_Ops"].ToString();
DBALabel.Text = dset.Tables[0].Rows[0]["DBA"].ToString();
CapacityPlanningLabel.Text = dset.Tables[0].Rows[0]["Capacity_Planning"].ToString();
BCPLabel.Text = dset.Tables[0].Rows[0]["BCP"].ToString();
DataCenterLabel.Text = dset.Tables[0].Rows[0]["Data_Center"].ToString();
GoldsmithLabel.Text = dset.Tables[0].Rows[0]["Goldsmith"].ToString();
AmericasITOpsLabel.Text = dset.Tables[0].Rows[0]["Americas_IT_Ops"].ToString();
APACITOpsLabel.Text = dset.Tables[0].Rows[0]["APAC_IT_Ops"].ToString();
EMEAITOpsLabel.Text = dset.Tables[0].Rows[0]["EMEA_IT_Ops"].ToString();
}
}
I imagine somehow telling the Formview what page to switch to when selecting from the dropdown but I haven't been able to figure out the coding for that. Thanks for your help!
One way to do this (the way I've done it in the past) would be to move your databound DropDownList outside of the FormView. Then, bind your FormView to a different SQLDataSource that's dependent on the DropDownLists SelectedValue. So you would have a DDL with all your Project Names:
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
DataSourceID="SqlDataSource1" DataTextField="Project_Name"
DataValueField="Project_Name">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="Your Connection String"
ProviderName="System.Data.SqlClient"
SelectCommand="SELECT DISTINCT [Project_Name] FROM [ProjectTable]">
</asp:SqlDataSource>
AND a FormView that is dependent upon what is selected in the DDL:
<asp:FormView ID="FormView1" runat="server" AllowPaging="True"
DataKeyNames="Project_Name" DataSourceID="SqlDataSource2">
...
</asp:FormView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="Your Connection String"
ProviderName="System.Data.SqlClient"
SelectCommand="SELECT * FROM [ProjectTable] WHERE Project_Name=#Project_Name">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownList1" Name="Project_Name"
PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
This way, when you click the "Edit" button in your FormView, you are editing the record you intended to edit.
As a side-note, your Code Behind leaves you very vulnerable to SQL Injection. I'd be careful about that. Instead of using string concatenation to generate that SELECT query, you should use Parameterized queries