dropdown list on showing selected item from list - c#

I have a dropdownList and it currently should be showing two items on list- when i am selecting the second one it goes back and shows the first item in the dropdown list.
This is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDown.DataTextField = "DisplayName";
DropDown.DataValueField = "ID";
DropDown.DataBind();
}
}
<asp:DropDownList ID="DropDown" runat="server"AutoPostBack="True" DataSourceID="Sections">
</asp:DropDownList>
<asp:SqlDataSource ID="Sections" runat="server" ConnectionString="<%$ ConnectionStrings:MyConnection %>" SelectCommand="SELECT e.DisplayName, e.ID , e.GUID
FROM .. e
INNER JOIN .. re
ON e.ID = re.anID
AND re.otherID = 1">
</asp:SqlDataSource>

Remove binding from design and try below code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDown.DataSourceID = Sections;
DropDown.DataTextField == "DisplayName";
DropDown.DataValueField = "ID";
DropDown.DataBind();
}
}
Thanks,
Hitesh

Just set your Dropdown Auto AutoPostBack to False.
<asp:DropDownList ID="DropDown" runat="server" DataTextField="DisplayName" DataValueField="ID" AutoPostBack="False" DataSourceID="Sections">
</asp:DropDownList>
<asp:SqlDataSource ID="Sections" runat="server" ConnectionString="<%$ ConnectionStrings:MyConnection %>" SelectCommand="SELECT e.DisplayName, e.ID , e.GUID
FROM .. e
INNER JOIN .. re
ON e.ID = re.anID
AND re.otherID = 1">
</asp:SqlDataSource>
Check this Url based on your new query: Populate one dropdownlist based upon action of another dropdownlist
Best Regards

Related

How to disable a dropdown list item when dropdown list is bound dynamically

Dropdown list is bound dynamically as:
<asp:DropDownList ID="ddlSource" class="ddl" runat="server" DataSourceID="FROM1" DataTextField="CompanyName" DataValueField="CompanyName">
</asp:DropDownList>
<asp:SqlDataSource ID="FROM1" runat="server" ConnectionString="<%$ ConnectionStrings:PIMSConnectionString2 %>" SelectCommand="SELECT [CompanyName] FROM Company ORDER BY [CompanyName]"></asp:SqlDataSource>
<br />
The CompanyName table has a value that is equal to "Select" and I want this value to be shown in the dropdown list but should be grayed out (disabled) so users can't select or set it.
Any idea how to do it in ASP.NET (not HTML)?
There is complete answer based on other questions from comments.
Make ListItems disabled and put them on the top of ddlSource based on condition CompanyName="Select" :
aspx :
<asp:DropDownList ID="ddlSource" class="ddl" runat="server" > </asp:DropDownList>
<asp:SqlDataSource ID="FROM1" runat="server" ConnectionString="<%$ ConnectionStrings:PIMSConnectionString2 %>" SelectCommand=""></asp:SqlDataSource>
<br />
code behind :
public void PopDDL()
{
FORM1.SelectCommand = "SELECT CompanyName FROM Company ORDER BY CASE WHEN CompanyName='Select' THEN 0 ELSE 1 END;"
ddlSource.DataSourceID = "FORM1";
ddlSource.DataTextField = "CompanyName";
ddlSource.DataValueField = "CompanyName";
ddlSource.DataBind();
foreach (ListItem itm in ddlSource.Items) {
if (itm.Value == "Select") {
itm.Attributes.Add("disabled", "disabled");
}
}
}
protected void Page_Load(object sender, System.EventArgs e)
{
PopDDL();
}
Try this, but populating ddlSource will be from code behind (it's in vb.net, sorry) :
Public Sub PopDDL()
FORM1.SelectCommand = "SELECT CompanyName FROM Company ORDER BY CompanyName;"
ddlSource.DataSourceID = "FORM1"
ddlSource.DataTextField = "CompanyName"
ddlSource.DataValueField = "CompanyName"
ddlSource.DataBind()
For Each itm As ListItem In ddlSource.Items
If itm.Value = *your_condition* Then 'condition why this item must be disabled
itm.Attributes.Add("disabled", "disabled")
End If
Next
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
PopDDL()
End Sub
Item will be displayed but disabled (gray).
Update :
I use conversion tool (vb.net to c#) and I think this is c# code :
foreach (ListItem itm in ddlSource.Items) {
if (itm.Value == *your_contidion*) { 'condition why this item must be disabled
itm.Attributes.Add("disabled", "disabled");
}
}
If You use itm.Enabled = False, item will not be showed.
UPDATE #2 (converted to c# code by online converter) :
aspx page :
<asp:DropDownList ID="ddlSource" class="ddl" runat="server" > </asp:DropDownList>
<asp:SqlDataSource ID="FROM1" runat="server" ConnectionString="<%$ ConnectionStrings:PIMSConnectionString2 %>" SelectCommand=""></asp:SqlDataSource>
<br />
code behind :
public void PopDDL()
{
FORM1.SelectCommand = "SELECT CompanyName FROM Company ORDER BY CompanyName;";
ddlSource.DataSourceID = "FORM1";
ddlSource.DataTextField = "CompanyName";
ddlSource.DataValueField = "CompanyName";
ddlSource.DataBind();
foreach (ListItem itm in ddlSource.Items) {
if (itm.Value == *your_condition*) {
itm.Attributes.Add("disabled", "disabled");
}
}
}
protected void Page_Load(object sender, System.EventArgs e)
{
PopDDL();
}

how to set passing variable in SelectCommand Asp.net

i try this example but not working.
<%string id = Request.QueryString["id"]; %>// get value and set in one variable
<%=id%>// display successfully variable's value
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [id], [name], [image], [old_price], [new_price] FROM [product] where [id]= "'<%=id%>'"" ></asp:SqlDataSource>
a problem in SelectCommand how to set variable in query i try like <%=id%>
Use the codebehind, for example in the Selecting event:
<asp:SqlDataSource ID="SqlDataSource1" ... OnSelecting="Product_Selecting">
Codebehind:
protected void Product_Selecting(object sender, SqlDataSourceCommandEventArgs e)
{
e.Command.Parameters[0].Value = Request.QueryString["id"];
}

How to check all checkboxes in a checkboxlist when page first loads?

Seems simple enough, but I can't figure it out. I've tried this code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
foreach (ListItem item in CheckBoxListDivision.Items)
item.Selected = true;
}
}
and this markup:
<asp:CheckBoxList ID="CheckBoxListDivision" runat="server" DataSourceID="SqlDataSourceDivisions" DataTextField="Divisions" DataValueField="Divisions" RepeatColumns="4">
</asp:CheckBoxList>
<asp:SqlDataSource ID="SqlDataSourceDivisions" runat="server" ConnectionString="<%$ ConnectionStrings:WebPortal_Call4HealthReports_ConnectionString %>" SelectCommand="usp_HR_DivisionsSelectAll" SelectCommandType="StoredProcedure"></asp:SqlDataSource>
Thank you for your time and effort.
The reason it's not selecting the items is that Page_Load event is called before binding the CheckBoxList items. So in order to select all the items when page loads you have two options:
First option: Put the same code you're using in the OnDataBound event of the CheckBoxList.
Modify the CheckBoxList markup to this:
<asp:CheckBoxList OnDataBound="CheckBoxListDivision_DataBound"
ID="CheckBoxListDivision" runat="server" DataSourceID="SqlDataSourceDivisions" DataTextField="Name" DataValueField="ID"
RepeatColumns="4" >
</asp:CheckBoxList>
And add this in code-behind:
protected void CheckBoxListDivision_DataBound(object sender, EventArgs e)
{
foreach (ListItem item in CheckBoxListDivision.Items)
{
item.Selected = true;
}
}
Second option: Remove the SqlDataSource from your markup and bind the CheckBoxList programatically in Page_Load event, then after binding the CheckBoxList, do the loop and you'll be able to select the items.
Hope this helps.

DetailsView DropDownLists

I am new to ASP.NET and currently having problem with dropdownlists in the DetailsView.
Exception error: System.InvalidOperationException: Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.
I have this code my code behind to refresh the list for the dropdownlists in DetailsView
protected void ddlVendor_SelectedIndexChanged
(object sender, EventArgs e)
{
DropDownList ddlVendorBB =
(DropDownList)DetailsView1.FindControl("VendorBUName");
if (ddlVendorBB != null)
{
Response.Write("SelectChanged");
ddlVendorBB.DataBind();
}
}
protected void SqlDataSourceProd_Selecting
(object sender, SqlDataSourceSelectingEventArgs e)
{
DropDownList ddlVendor =
(DropDownList)DetailsView1.FindControl("VendorName");
if (ddlVendor != null)
{
e.Command.Parameters["#VendorID"].Value = ddlVendor.SelectedValue;
}
}
These two dropdownlists in the DetailsView
<EditItemTemplate>
<asp:DropDownList id="VendorName"
datasourceid="VendorSqlDataSource"
AutoPostBack="true"
datatextfield="VendorName"
DataValueField="VendorID"
SelectedValue='<%# Bind("VendorID") %>'
runat="server"
OnSelectedIndexChanged="ddlCategory_SelectedIndexChanged" />
<asp:SqlDataSource ID="VendorSqlDataSource"
ConnectionString="<%$Connectionstrings:ConnectionString%>"
SelectCommand="SELECT VendorID, VendorName from MDF_Vendor"
runat="server">
</asp:SqlDataSource>
</EditItemTemplate>
<EditItemTemplate>
<asp:DropDownList id="VendorBUName"
datasourceid="VendorBUSqlDataSource"
datatextfield="VendorBUName"
DataValueField="VendorBUID"
SelectedValue='<%# Bind("VendorBUID") %>'
runat="server"/>
<asp:SqlDataSource ID="VendorBUSqlDataSource"
runat="server"
ConnectionString="<%$Connectionstrings:ConnectionString%>"
selectcommand="SELECT VendorBUID, VendorBUName
from MDF_VendorBU
Where VendorID = #VendorID"
OnSelecting="SqlDataSourceProd_Selecting">
<SelectParameters>
<asp:Parameter Name="VendorID" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</EditItemTemplate>
Problem is:
If I leave SelectedValue= there, the dropdownlists in Edit mode seletected the correct value in the items listed when I first click Edit, but when I select a new VendorName, it errors "Databining method such as Eval(), Xpath(), and Bind()... ".
Now, if I removed the Selectedvalued for the dropdownlists, it will work for refreshing the VendorBUName when select a new VendorName, but NOT not selected the default VendorID when I click "Edit". It just list the VendorName list without selected the current VendorID one.
Can someone please let me know what wrong in my codes? Thanks!
As the error states, you cannot use Bind where you are trying to use it. You should be able to use the DataBinder though
SelectedValue='<%# DataBinder.Eval (Container.DataItem, "VendorBUID") %>'
Edit: Since binding a value to the SelectedValue with DataBinder didn't work, you can try to set the value when binding data. Provided dataSource is some instance of a class that has a property called VendorBUID, something similar to this might work in
public override void OnLoad(EventArgs e) {
VendorBUName.DataBinding += dataBindDropDown;
}
private void dataBindDropDown(object sender, EventArgs e) {
VendorBUName.SelectedValue = dataSource.VendorBUID;
}

Catching null values on databinding

I have a dropdownlist that is populated from an SQL select statement. The select statement filters for items where the 'bit' is set to false and the items, although still in the database are hidden.
My problem is; when an item is out of stock or hidden (bit = false) the user may still have items that are now hidden so it throws an error. How and where can I catch this, show the original item or set the value to default?
protected void GradeDropDownList_DataBinding (object sender, EventArgs e)
{
var ddl = (DropDownList)(sender);
var a = ((Label)MyDetailsView.FindControl("GradeLabelEdit")).Text;
a = a.Trim();
if (a != "") { ddl.SelectedValue = a; }
}
The select statement;
<asp:SqlDataSource ID="getGrade" runat="server" ConnectionString="<%$ ConnectionStrings:CasesTimeConnection %>"
SelectCommand="SELECT [gradeID], [gradeText] FROM [user_grades] WHERE ([visibleState] = #visibleState)">
<SelectParameters>
<asp:Parameter DefaultValue="True" Name="visibleState" Type="Boolean" />
</SelectParameters>
</asp:SqlDataSource>
In page;
<EditItemTemplate>
<asp:DropDownList ID="GradeDropDownList" runat="server" DataSourceID="getGrade" DataTextField="gradeText" DataValueField="gradeID" OnDataBinding="GradeDropDownList_DataBinding" OnSelectedIndexChanged="GradeDropDownList_SelectedIndexChanged">
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="gradeLabel" runat="server" Text='<%# Bind("gradeText") %>'></asp:Label>
</ItemTemplate>
Retrieve LastModifiedDate while retrieving the records and while trying to update the record check the existing lastModifiedDate value with the one you retrieved. If they are different then throw an alert message / display new quantity.
Thanks
Shashi

Categories

Resources