ASP.NET Get value from DropDownList in EditItemTemplate in codebehind - c#

I have a GridView that I have placed in DropDownList's in 2 columns.
<asp:TemplateField HeaderText="Upgrade" SortExpression="Upgrade">
<ItemTemplate>
<asp:Label ID="LabelUpgrade" runat="server" Text='<%# Eval("Upgrade") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlUpgrade" runat="server" Width="100px">
<asp:ListItem Value="1">--Select--</asp:ListItem>
<asp:ListItem Value="2">1</asp:ListItem>
<asp:ListItem Value="3">2</asp:ListItem>
<asp:ListItem Value="4">3</asp:ListItem>
<asp:ListItem Value="5">4</asp:ListItem>
<asp:ListItem Value="6">5</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
how do I grab the item from ddlUpgrade in the codebehind?
OnUpdating Event - I don't have a way to pull the row to get the value from the drop down but I add my sql parameters here.
protected void IAP_Updating(object sender, SqlDataSourceCommandEventArgs e){}
RowUpdating Event - I can get the row here but I can't add the value to the sql parameters because e.command isn't valid here
protected void gvClients_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow _row = gvClients.Rows[e.RowIndex];
DropDownList _ddl = (DropDownList)_row.FindControl("ddlUpgrade");
SqlParameter _parm = new SqlParameter("#Upgrade", _ddl.SelectedItem.ToString());
}

On the RowUpdating event you can capture the control inside the edit template based on its ID.
GridViewRow row = GridView1.Rows[e.RowIndex];
DropDownList ddl = (DropDownList)row.FindControl("ddlUpgrade");
SqlParameter _parm = new SqlParameter("#Upgrade", ddl.SelectedItem.ToString());
e.Command.Parameters.Add(_parm);

I would add a hidden field outside the GridView:
<asp:HiddenField ID="hdnSelection" value="" runat="server" />
And change the gvClients_RowUpdating method:
protected void gvClients_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow _row = gvClients.Rows[e.RowIndex];
DropDownList _ddl = _row.FindControl("ddlUpgrade") as DropDownList;
if(_ddl != null)
{
hdnSelection.Value = _ddl.SelectedItem.Text;
IAP.Update();//Assuming IAP is the ID of the SqlDataSource
}
}
And my IAP_Updating method should look like this:
protected void IAP_Updating(object sender, SqlDataSourceCommandEventArgs e)
{
SqlParameter _parm = new SqlParameter("#Upgrade", hdnSelection.Value);
e.Command.Parameters.Add(_parm);
}
I did not test the code. You may need to tweak.

Related

Getting value from dropdown in gridview

i am trying to make a "clock in / out site" and one of the functions is for the user to edit old clock ins/outs. i have added a dropdown with 2 values "IND" and "UD". How do i get these values out, and send them to my "CHECKIN" sql value. I hope you know what iam trying to explain.
this is what it looks like:
The Dropdown:
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="DropDownList2" runat="server"
OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged">
<asp:ListItem Selected="True">Ind</asp:ListItem>
<asp:ListItem Value="UD">Ud</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
what ive tried:
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
string val = row.Cells[3].ToString();
SqlDataSource1.SelectParameters.Add("CHECKEDIN", val);
}
and aswell as:
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)GridView1.FindControl("DropDownList2");
string val = ddl.SelectedValue;
SqlDataSource1.SelectParameters.Add("CHECKEDIN", val);
}
Both of these return "null" tho
Use RowDataBound event of GridView.
Code
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow
&& GridView1.EditIndex == e.Row.RowIndex)
{
DropDownList ddl = (DropDownList)e.Row.FindControl("DropDownList2");
string val = ddl.SelectedValue.ToString();
SqlDataSource1.SelectParameters.Add("CHECKEDIN", val);
}
}
You can cast the sender back to a DropDownlist and get the selected value
DropDownList dropDownList = sender as DropDownList;
string val = dropDownList.SelectedValue;
But how will you know with this method which row the DropDownList belongs to?
You can use a trick for that, like abusing the CSS class to get the correct row number.
<asp:DropDownList ID="DropDownList2" runat="server" OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged" AutoPostBack="true" CssClass='<%# Container.DataItemIndex %>'>
And get the row number in code behind.
int rowNumber = Convert.ToInt32(dropDownList.CssClass);

Dropdownlist in edit mode of a gridview

In my application in c#, when I edit a row in the gridview I choose some new data from a dropdownlist.
I am populating the dropdown like this:
<asp:TemplateField HeaderText="Gender">
<ItemTemplate>
<asp:Label ID="gender" runat="server" Text='<%# Eval("gender").ToString() %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="DDL_genderList" runat="server">
<asp:ListItem Value="" Text="---"></asp:ListItem>
<asp:ListItem Value="M" Text="M"> </asp:ListItem>
<asp:ListItem Value="F" Text="F"> </asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
But when I press the 'Edit' button from the template and enters in the 'RowUpdating' event, the selected value from the dropdownlist is every time the first value from that dropdownlist.
I need selected value in dropdownlist it's the value which displays in Label gender.
Does anyone have any ideas?
I've tried many ways to set the selected value in the 'RowDataBound' event, but with no luck.
I tried this:
protected void gvProducts_RowDataBound(object sender, GridViewRowEventArgs e)
{
DataRowView dRowView = (DataRowView)e.Row.DataItem;
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList genderList = (DropDownList)e.Row.FindControl("DDL_genderList");
genderList.SelectedValue = dRowView[1].ToString();
}
}
You have to find Label from TemplateField (DataRow) and DropDownList from EditTemplate (EditRowState) as like:
protected void gvProducts_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// find gender from label which is inside ItemTemplate
string lblgender = ((Label)e.Row.FindControl("gender")).Text;
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
// find gender list from dropdownlist which is inside EditTemplate
DropDownList genderList = (DropDownList)e.Row.FindControl("DDL_genderList");
genderList.SelectedIndex =
genderList.Items.IndexOf(genderList.Items.FindByValue(lblgender));
}
}
}
I know this is very late answer but it can help to the OP.

Drop-down Selected Value not Showing in my Detailview

I have drop-down that is not showing the previoiusly selected value in my Detailview. It always shows me the first value in the list. If the previously selected value was xyz then when the Detailvies loads, i want to show xyz. I have researched a lot but could not find any solution that i can use. please help
here is my aspx code for the field that has the dropdown
<asp:TemplateField HeaderText="Name:">
<ItemTemplate>
<asp:Label ID="lbl_UID" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Name") %>'></asp:Label></ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddl_Name" Width="200px" Height="25" DataSourceID="SDS_Manager" DataTextField="FULL_NM" AutoPostBack="false"
DataValueField="UID" runat="server" AppendDataBoundItems="false">
<asp:ListItem Text="Select Name" Value="Select Name"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
here is the code behind that binds the detailview
protected void Edit(object sender, EventArgs e)
{
using (GridViewRow row = (GridViewRow)((LinkButton)sender).Parent.Parent)
{
sqlcon.Open();
sqlcmd = new SqlCommand(#"Select PRJ_ID, WPC_CD, WPC_DESC, Name FROM myTable where PRJ_ID = '" + myvar + "' ", sqlcon);
da = new SqlDataAdapter(sqlcmd);
da.Fill(dt);
sqlcon.Close();
DV_Edit.DataSource = dt;
DV_Edit.DataBind();
sqlcon.Close();
popup.Show();
}
}
Try setting AutoPostBack="true" and make sure if you have any logic to set the value of the drop down in the page load, that the code is not executed on post back as shown below.
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
ddlOne.DataSource = //your data here;
ddlOne.DataBind();
}
}
//if you don't wrap this logic in the if(!IsPostBack), the code will simply re-populate
//the drop down and set the selected index to the first item in the list with each
//post back.

C# Dynamic created dropdownlist not binding after FormView Update

I am having trouble getting my dropdownlist to populate after I update the sqldatasource or change FormView Modes. The dropdown is created from an array in the code behind. I will post the snips of code below. The dropdown binds as expected until these events.
Any assistance in why this does not work would be awesome.
<asp:FormView ID="FormView1" runat="server" DataKeyNames="ID" DataSourceID="tbl_PreRegistration"
Width="100%" CssClass="c2wForm" DefaultMode="Edit">
<EditItemTemplate>
<asp:DropDownList ID="stateDDL" runat="server" OnSelectedIndexChanged="State_DDL_SelectedIndexChanged"
CausesValidation="false" AutoPostBack="true">
</asp:DropDownList>
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update"
Text="Update" CssClass="button blue" />
<asp:LinkButton ID="btnReset" runat="server" CausesValidation="False"
Text="Cancel" CssClass="button white" OnClick="btnReset1_Click" />
</ContentTemplate></asp:UpdatePanel>
</EditItemTemplate>
</asp:FormView>
CODE BEHIND:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
populateStateDDL("stateDDL", "CA");
}
}
protected void populateStateDDL(string DDL_ID, string getCurrentValue)
{
DropDownList strDDL_ID = (DropDownList)FormView1.FindControl(DDL_ID);
ArrayList states = new ArrayList();
strDDL_ID.DataValueField = "Value";
strDDL_ID.DataTextField = "Text";
strDDL_ID.DataSource = formating.GetAllStates();
strDDL_ID.DataBind();
strDDL_ID.SelectedValue = getCurrentValue.ToUpper();
}
you need to create the control every time, not just when postback = false. the control should be rendered in the Init event so that it can then be wired into viewstate and all that other webforms stuff.
here is some pseudo-code
private DropDownList ctrl;
protected override void Init(EventArgs e)
{
base.Init(e);
ctrl = new DropDownList
{
Id = "name of control",
DataValueField = "Value",
DataTextField = "Text"
};
Controls.Add(ctrl);
}
protected override void Load(EventArgs e)
{
base.Load(e);
if(ispostback) return;
ctrl.DataSource = GetData();
DataBind();
}

Rebinding on Postback Based on Selected DropDown Value

Greetings!
I have a DropDownList within a FormView which are bound to XmlDataSources:
<asp:FormView ID="MyFormView" runat="server" DataSourceID="MyXmlDataSource">
<ItemTemplate>
<h1><%# XPath("SomeNode")%></h1>
<asp:Label ID="MyLabel" runat="server" AssociatedControlID="MyDdl" Text='<%# XPath("SomeOtherNode")%>' />
<asp:DropDownList ID="MyDdl"
runat="server"
DataSourceID="MyDdlDataSource"
DataTextField="name"
DataValueField="value"
AutoPostBack="true"
OnSelectedIndexChanged="MyDdl_SelectedIndexChanged">
</asp:DropDownList>
</ItemTemplate>
</asp:FormView>
<asp:XmlDataSource ID="MyXmlDataSource" runat="server" XPath="Root/MainSection" />
<asp:XmlDataSource ID="MyDdlDataSource" runat="server" XPath="Root/MainSection/Areas/*" />
In the page's codebehind, I have the following OnLoad() method as well as the method for when the select index of the dropdownlist changes:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!IsPostBack)
{
string xml = GetMyXml(0); // default value
MyXmlDataSource.Data = xml;
MyDdlDataSource.Data = xml;
}
}
protected void MyDdl_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList l_MyDdl = FindControl("MyDdl") as DropDownList;
int myVal;
if (l_MyDdl != null)
if (!Int32.TryParse(l_MyDdl.SelectedItem.Value, out myVal))
myVal = 0;
string xml = GetMyXml(myVal);
MyXmlDataSource.Data = xml;
MyDdlDataSource.Data = xml;
}
When a different value is selected from the dropdown list and SelectedIndexChanged is invoked, I am unable to get the value of the dropdown list (FindControl always returns null) in order to use it to re-bind the datasources. How can I get this value?
Because your dropdownlist is contained within another control it may be that you need a recursive findcontrol.
http://weblogs.asp.net/palermo4/archive/2007/04/13/recursive-findcontrol-t.aspx

Categories