Retrieve DropDownList value in RowUpdating event asp.net - asp.net

Here is my aspx code:
<EditItemTemplate>
<asp:DropDownList ID="ddlTotalColumn" runat="server">
<asp:ListItem Value="">Select value</asp:ListItem>
<asp:ListItem Value="0">1</asp:ListItem>
<asp:ListItem Value="1">2</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
My aspx.cs code:
protected void gvTest_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow selected_row = gvTest.Rows[e.RowIndex];
var total_column_drop_down_list = (DropDownList)selected_row.FindControl("ddlTotalColumn");
int column_string = Convert.ToInt32(total_column_drop_down_list.SelectedItem.Value);
gvTest.EditIndex = -1;
...
}
At this line: int column_string = Convert.ToInt32(total_column_drop_down_list.SelectedItem.Value);
I have an error: "Input string was in incorrect format" because "total_column_drop_down_list.SelectedItem.Value" will return empty string ("").
So is there any bright idea?

It sounds like you have made the classic mistake of not putting your databinding code inside a if (!Page.IsPostBack) block. Thus, your GridView re-binds, and you get default values in your RowUpdating event (rather than what you selected).
Wherever you are binding your GridView, in Page_Load for instance, you need to do this:
if (!Page.IsPostBack)
{
BindGrid();
}
Where "BindGrid()" is whatever code you call to databind your GridView.
On a slightly unrelated note, you can actually use the GridViewUpdateEventArgs parameter that's passed to that method to grab the updated values (rather than using FindControl to get the DropDownList, and then getting the values).

Related

How to get the repeater-item in a Checkbox' CheckedChanged-event?

I have a CheckBox inside a Repeater. Like this:
<asp:Repeater ID="rptEvaluationInfo" runat="server">
<ItemTemplate>
<asp:Label runat="server" Id="lblCampCode" Text="<%#Eval("CampCode") %>"></asp:Label>
<asp:CheckBox runat="server" ID="cbCoaching" value="coaching-required" ClientIDMode="AutoID" AutoPostBack="True" OnCheckedChanged="cbCoaching_OnCheckedChanged" />
</ItemTemplate>
</asp:Repeater>
When some one clicks on the checkbox I want to get that entire row in my code behind. So if a CheckedChanged happens I want to get the Text of the Label lblCampCode in code behind.
Is it possible?
I have managed to write this much code.
protected void cbCoaching_OnCheckedChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
Repeater rpt = (Repeater)chk.Parent.Parent;
string CampCode = "";// here i want to get the value of CampCode in that row
}
So you want to get the RepeaterItem? You do that by casting the NamingContainer of the CheckBox(the sender argument). Then you're almost there, you need FindControl for the label:
protected void cbCoaching_OnCheckedChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
RepeaterItem item = (RepeaterItem) chk.NamingContainer;
Label lblCampCode = (Label) item.FindControl("lblCampCode");
string CampCode = lblCampCode.Text;// here i want to get the value of CampCode in that row
}
This has the big advantage over Parent.Parent-approaches that it works even if you add other container controls like Panel or Table.
By the way, this works the similar way for any databound web-control in ASP.NET (like GridView etc).

Not able to access edit template field dropdownlist in gridview

I am using a gridview which is having dropdownlist in edittemplate field. There are 3 list items in dropdown : Red,Amber,Green. Instead of displaying text in listitems, I want to show the colors, for the same I am using dropdownlist's onLoad event, however this event is not able to recognize the dropdownlist.
Dropdownlist Designer code :
<asp:TemplateField HeaderText="Color">
<EditItemTemplate>
<asp:DropDownList ID="ddlcolor" runat="server" AppendDataBoundItems="true" DataTextField="COLOR" DataValueField ="COLOR" OnLoad="DDLColor_Load">
<asp:ListItem Value="-1">- Select Color -</asp:ListItem>
<asp:ListItem Value="0">Amber</asp:ListItem>
<asp:ListItem Value="1">Green</asp:ListItem>
<asp:ListItem Value="2">Red</asp:ListItem>
</asp:DropDownList></EditItemTemplate></asp:TemplateField>
Dropdownlist onLoad Event in codebehing :
protected void DDLColor_Load(object sender, EventArgs e)
{
for (int i = 0; i < ddlcolor.Items.Count; i++)
{
ddlcolr.Items[i].Attributes.Add("style", "background-color:" + ddlcolor.Items[i].Text);
}
}
However, it shows that the dropdownlist ddlcolor does not exists in current context.
Do I need to find this control in gridview ? Please suggest.
You are right. You need to find the control. Using the sender argument will help you locate the drop down without using the find control method
protected void DDLColor_Load(object sender, EventArgs e)
{
DropdownList ddlcolr=(Dropdownlist)sender;
for (int i = 0; i < ddlcolor.Items.Count; i++)
{
ddlcolr.Items[i].Attributes.Add("style", "background-color:" + ddlcolor.Items[i].Text);
}
}

DetailsView: How to set a HiddenField value using the CommandArgument on a New command?

I have inherited some code that has a GridView and a DetailsView in a webpart control.
The DetailsView is able to create two different kinds of an object e.g. TypeA and TypeB.
There's a dropdown list that filters the GridView by object type and the DetailsView has an automatically generated Insert button.
<asp:DetailsView ID="myDetailsView"
AutoGenerateInsertButton="True"
AutoGenerateEditButton="True"
AutoGenerateRows="false"
OnItemUpdating="OnItemUpdating"
DefaultMode="ReadOnly"
OnDataBound="OnDetailsViewBound"
OnItemInserting="OnItemInserting"
OnModeChanging="OnDetailsViewModeChanging"
runat="server">
I have been asked to:
remove the filter on the GridView; and
split the New buttons/links into two so there's a separate button for creating each type of object.
Removing the filter means that I need some other way to track what kind of object we're creating.
I have split the New links by changing the above to:
<asp:DetailsView ID="myDetailsView"
AutoGenerateInsertButton="False"
AutoGenerateEditButton="True"
AutoGenerateRows="false"
OnItemUpdating="OnItemUpdating"
DefaultMode="ReadOnly"
OnDataBound="OnDetailsViewBound"
OnItemInserting="OnItemInserting"
OnModeChanging="OnDetailsViewModeChanging"
runat="server">
and adding
<FooterTemplate>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="lnkCreateNewTypeA" CommandName="New" CommandArgument="TypeA" CssClass="buttonlink">New Type A</asp:LinkButton>
<asp:LinkButton runat="server" ID="lnkCreateNewTypeB" CommandName="New" CommandArgument="TypeB" CssClass="buttonlink">New Type B</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</FooterTemplate>
I haven't yet removed the filter so the changes currently function the same as before, as I'm using the New command.
What I was hoping to be able to do is somehow capture the New event so I can put the CommandArgument value into a hidden field, that the DetailsView would then use to determine which type of object it's creating and also to show/hide fields.
When I put breakpoints in all of the event handlers in my code, the first one to break is OnDetailsViewModeChanging, which doesn't have access to the CommandArgument.
OnItemCommand (if it's hooked up) is triggered when any button within the DetailsView is pressed and does give me access to the CommandArgument but I'm not sure what exactly needs to be done within this method to mimic the chain of events that occurs when you use automatically generated buttons.
Is my only option for retrieving the CommandArgument to capture it in the OnItemCommand event handler or is there some other event that is triggered on the New command?
Can anyone explain to me the sequence of events that occurs when the New command is triggered?
I read somewhere that it changes the mode to Insert but I don't know what else it does. I believe the OnItemInserting method isn't called until the "Insert" link is clicked.
Any help would be gratefully received!!
Edit:
I have found this link on DetailsView events but it hasn't answered my question.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.detailsview_events.aspx
Edit:
I have tried adding the following:
in ascx:
<asp:DetailsView ID="myDetailsView"
...
OnItemCommand="OnItemCommand"
...
runat="server">
...
<asp:TemplateField HeaderText="Object Type" HeaderStyle-CssClass="columnHeader">
<ItemTemplate>
<asp:HiddenField runat="server" ID="hidObjectType" Value=""/>
<asp:Label runat="server" ID="lblObjectType"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
in code behind:
protected void OnItemCommand(object sender, DetailsViewCommandEventArgs e)
{
if (e.CommandName.Equals("New"))
{
var objectType = e.CommandArgument.ToString();
HiddenField typeHidden = this.myDetailsView.FindControl("hidObjectType") as HiddenField;
if (typeHidden != null)
{
typeHidden.Value = objectType;
}
Label typeLabel = this.myDetailsView.FindControl("lblObjectType") as Label;
if (typeLabel != null)
{
typeLabel.Text = objectType;
}
}
}
I found that I didn't need to set the mode (this.myDetailsView.ChangeMode(DetailsViewMode.Insert);) in this method, as the OnDetailsViewModeChanging event handler still triggered.
This finds the controls and sets the values on them correctly. If I check the values again in OnDetailsViewModeChanging, their values are still set but as part of the logic in this method, there is a call to
this.myDetailsView.DataBind()
which causes a postback and at this point, the values are lost. I tried adding
EnableViewState="True"
but this made no difference. I've reviewed the page lifecycle (http://spazzarama.files.wordpress.com/2009/02/aspnet_page-control-life-cycle.pdf) and thought that maybe this.EnsureChildControls() would help but it's also made no difference.
An alternative would be to store the value in the session but I'd rather not.
As far as I can tell there is no event for capturing the "New" command aside from OnItemCommand, which captures all commands. (NOTE: You will need to make sure that CausesValidation="False" is set on your LinkButton or the code won't break into OnItemCommand).
When stepping through the code, the following occurred:
After the linkbutton was pressed, OnItemCommand is triggered. CommandName = "New" and here I could retrieve the CommandArgument
Next OnModeChanging is triggered. e.NewMode = "Insert". From all examples I've seen, here you call ChangeMode on the DetailsView and then call Databind() on it
Next OnDataBound is triggered as a result of calling Databind()
I didn't find a way to retain the value of the hidden variable between the various events so I ended up using a session variable. Code is below in case anyone wants it.
DetailsView declaration in the ASCX:
<asp:DetailsView ID="myDetailsView"
AutoGenerateInsertButton="False"
AutoGenerateEditButton="True"
AutoGenerateRows="false"
OnItemInserting="OnItemInserting"
OnItemUpdating="OnItemUpdating"
OnItemCommand="OnItemCommand"
DefaultMode="ReadOnly"
OnDataBound="OnDetailsViewBound"
OnModeChanging="OnDetailsViewModeChanging"
runat="server">
In the code-behind:
constant declarations...
private const string SESSIONKEY_MYVALUE = "MyValue";
private const string DEFAULT_OBJECTTYPE = "TypeA";
OnItemCommand event handler...
protected void OnItemCommand(object sender, DetailsViewCommandEventArgs e)
{
if (e.CommandName.Equals("New", StringComparison.InvariantCultureIgnoreCase))
{
var objectType = e.CommandArgument.ToString();
HiddenField typeHidden = this.myDetailsView.FindControl("hidObjectType") as HiddenField;
if (typeHidden != null)
{
typeHidden.Value = objectType;
}
HttpContext.Current.Session[SESSIONKEY_MYVALUE] = objectType;
}
}
OnModeChanging event handler....
protected void OnDetailsViewModeChanging(Object sender, DetailsViewModeEventArgs e)
{
if (e.NewMode == DetailsViewMode.Insert)
{
this.myDetailsView.ChangeMode(DetailsViewMode.Insert);
this.myDetailsView.DataBind();
}
}
OnDataBound event handler...
protected void OnDetailsViewBound(object sender, EventArgs e)
{
if (this.myDetailsView.CurrentMode == DetailsViewMode.Insert)
{
var sessionVar = HttpContext.Current.Session[SESSIONKEY_MYVALUE];
var objectType = sessionVar == null ?
DEFAULT_OBJECTTYPE :
sessionVar.ToString();
var typeHidden = this.myDetailsView.FindControl("hidObjectType") as HiddenField;
if (typeHidden != null)
{
typeHidden.Value = objectType;
}
}
}

RadioButtonList selection IndexChanged

My Scenario,
When i select the option in list i need to perform some action like Textbox should be disabled. But i don find my breakpoint pointing to that action to be performed.Pls help
I guess you mean the SelectedIndexChanged event does not fire that is so because you'vent set the AutoPostBack to true.
<asp:RadioButtonList ID="RadioButtonList1" runat="server" AutoPostBack="True"
onselectedindexchanged="RadioButtonList1_SelectedIndexChanged">
</asp:RadioButtonList>
Code
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox4.Enabled = false;
}

Why won't my LinkButton inside a GridView raise its OnClick event?

I have a LinkButton inside a GridView (via an TemplateField). No matter what I try, the LinkButton will not invoke its event handler. I have tried both:
A traditional event handler ("OnClick")
A OnRowCommand event handler at the GridView level.
In both cases, I've debugged and it doesn't even catch the event handler.
If I move the LinkButton out on the page (so it's not in the GridView), it works fine, so I know the syntax is right.
Here is the "traditional" method:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton Text="Cancel" ID="DeleteButton" CausesValidation="false" OnClick="CancelThis" runat="server" />
</ItemTemplate>
<asp:TemplateField>
What's interesting is if I remove the "CancelThis" method from the code behind, it throws an error. So I know it's aware of its event handler, because it looks for it when it compiles.
Here is the RowCommand method:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton Text="Cancel" ID="DeleteButton" CausesValidation="false" CommandName="CancelThis" runat="server" />
</ItemTemplate>
<asp:TemplateField>
In this case, the GridView has:
OnRowCommand="GridView_RowCommand"
It postsback, but never hints at raising the event.
Any idea what I'm missing here?
How are you binding your GridView? Are you using a datasource control? If you are binding manually during Page_Load, it's possible that since the grid is binding every round trip, the event handler isn't catching properly. If this is the case, you may want to try something like:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
//do binding
}
}
Can you post sample binding code to go with your markup?
If you really want to force the issue, you could hook into the RowDataBound event on the Grid, find the button manually and add the handler in the code behind. Something like:
markup snippet:
<asp:GridView ID="gvTest" runat="server" OnRowDataBound="gvTest_RowDataBound" />
code behind:
protected void gvTest_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
//find button in this row
LinkButton button = e.Row.FindControl("DeleteButton") as button;
if(button != null)
{
button.Click += new EventHandler("DeleteButton_Click");
}
}
}
protected void DeleteButton_Click(object sender, EventArgs e)
{
LinkButton button = (LinkButton)sender;
// do as needed based on button.
}
I'm not sure what the purpose of the button is, but assuming it is a row delete button, you may not want to take this approach as in the event handler, you don't have direct access to the row in question, like you would using the RowCommand event.
Is there a reason you're using the Template field? Vs say a ButtonField? If you use a ButtonField, then you can hook into the RowCommand event.
markup snippet:
<asp:GridView ID="gvTest" runat="server" OnRowCommand="gvTest_RowCommand">
<columns>
<asp:buttonfield buttontype="Link" commandname="Delete" text="Delete"/>
....
</columns>
</asp:GridView>
code behind:
protected void gvTest_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName == "Delete")
{
//take action as needed on this row, for example
int rowIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow currentRow = (sender as GridView).Rows[rowIndex];
//do something against the row...
}
}
You might want to consult MSDN docs on some of these topics:
RowCommandEvent
ButtonField class
EDIT:
To answer your question on the ButtonField - yes I don't see why you couldn't still deal with a buttonfield. Here's a snippet to find the buttonfield during row data bound and hide it (untested but I think would work...)
protected void gvTest_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//let's assume your buttonfield is in column 1
// (you'd know this based on your markup...)
DataControlFieldCell cell = e.Row.Cells[1] as DataControlFieldCell;
if(cell != null)
{
ButtonField field = cell.ContainingField as ButtonField;
//based on your criteria, show or hide the button
field.Visible = false;
//or
field.Visible = true;
}
}
}
Is viewstate turned on on your GridView? This has caught me out numerous times.
<button onclick="window.open('<%#Eval("ReportLinks")%>', '_blank');" title='<%#Eval("ReportLinks")%>'> Link</button>

Resources