Event Handler OnItemCommand with TextBox control - asp.net

I have Repeater that contains a TextBox and a LinkButton. When the LinkButton is clicked, I need to grab the TextBox.Text and do stuff …
Using the EVENT Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e) I am able to get the value of the TextBox using TextBox tx = e.Item.FindControl("txCode") as TextBox
However
Using the EVENT Repeater1_ItemCommand(object sender, RepeaterCommandEventArgs e) I am NOT getting anything back. The TextBox is empty.
How can I get the text/content from the TextBox using 'OnItemCommand'?
<asp:Repeater ID="Repeater1" runat="server" onitemdatabound="Repeater1_ItemDataBound" OnItemCommand="Repeater1_ItemCommand">
<ItemTemplate>
<li>
<asp:TextBox ID="txCode" runat="server"></asp:TextBox>
<asp:LinkButton CommandName="verifyCode" ID="lbCode" runat="server">Submit<asp:LinkButton>
</li>
</ItemTemplate>
</asp:Repeater>
I am able to get the TextBox Value below
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
TextBox tx = e.Item.FindControl("txCode") as TextBox;
string myText = tx.Text; '<--- working
}
I am NOT able to get the TextBox Value below
protected void Repeater1_ItemCommand(object sender, RepeaterCommandEventArgs e)
{
if (e.CommandName == "verifyCode")
{
TextBox tx = e.Item.FindControl("txCode") as TextBox;
string myText = tx.Text; '<--- NOT working
}

Do not bind your Repeater to it's DataSource on every postback. Otherwise ViewState cannot be reloaded correctly what causes issues like this.
So always check the IsPostBack property in Page_Load when ViewState is enabled(EnableViewState=true):
if(!IsPostBack)BindRepeaterToDataSource();

Related

Change GridView Custom Button Text and Css on click event

I am working on a project where I am creating a dashboard for the Admin.
I have a UsersGridView which displays the data of the registered users in it.
Using the Template field for the Gridview I have created a button for that allows the Admin to with Lockout or Enable the user's to use the system.
<asp:TemplateField HeaderText="LockoutStatus">
<ItemTemplate>
<asp:Button ID="LockoutStatus" runat="server" CausesValidation="false" CommandName="LockoutStatus" Text="Enabled"
CommandArgument='<%# Eval("Id") %>' />
</ItemTemplate>
</asp:TemplateField>
In the RowCommand event how can I change the button CssClass and text if the user is locked out from the system.
There are several ways you can change the CssClass.
With the RowDataBound event.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//check if the row is d datarow
if (e.Row.RowType == DataControlRowType.DataRow)
{
//cast the row back to a datarowview
DataRowView row = e.Row.DataItem as DataRowView;
//use findcontrol to locate the butotn
Button btn = e.Row.FindControl("LockoutStatus") as Button;
//change the class based on a column value
if (row["ColumnName"].ToString() == "LockedOut")
{
btn.CssClass = "ClassA";
}
}
}
Or on the aspx page with a ternary operator.
<asp:Button ID="LockoutStatus" runat="server"
CssClass='<%# Eval("ColumnName").ToString() == "LockedOut" ? "ClassA" : "ClassB" %>'
Or as you wanted in the RowCommand event. You can use the CommandSource and cast it to a Button.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
Button btn = e.CommandSource as Button;
btn.CssClass = "ClassA";
}

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).

Why is my repeater control empty on postback?

I think this is a "doh" moment caused by me not having dome WebForms dev for a few years..
I have a repeater which which contains a bunch of checkboxes:
<asp:Repeater EnableViewState="true" ID="IDTypesRepeater" runat="server" OnItemDataBound="IdTypesRepeaterItemDataBound">
<HeaderTemplate/>
<ItemTemplate>
<asp:CheckBox EnableViewState="true" ID="chkIdType" Text="<%# ((KeyValuePair<string,int>)Container.DataItem).Key %>" runat="server" />
<asp:HiddenField ID="idType" Value="<%# ((KeyValuePair<string,int>)Container.DataItem).Value %>" runat="server"/>
<br />
</ItemTemplate>
</asp:Repeater>
I need to get the checkboxes that are selected in the code behind:
foreach (RepeaterItem repeaterItem in IDTypesRepeater.Items)
{
if ( ((CheckBox)repeaterItem.FindControl("chkIdType")).Checked )
{
// Do something
}
}
But on postback, this code isn't working! I know about always databinding a repeater, so I've done this:
protected void Page_Load(object sender, EventArgs e)
{
IDTypesRepeater.DataSource = DocTemplateHelper.GetApplicableIDTypes().Where(type => type.Value != 0);
IDTypesRepeater.DataBind();
}
So this repopulates the repeater, but the Update code never finds any checked checkboxes.. Any ideas?
Bind in the Page_Init event
protected void Page_Init(object sender, EventArgs e)
{
IDTypesRepeater.DataSource = DocTemplateHelper.GetApplicableIDTypes().Where(type => type.Value != 0);
IDTypesRepeater.DataBind();
}
Be sure to use the !Page.IsPostBack method in your pageload.
Otherwise, the Repeater will keep getting reset, and all your checkboxes
will be in there default value (unchecked)
This should fix it. You are binding the control on postback hence losing the values. You can bind it after handling any event to show the updated record.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
IDTypesRepeater.DataSource = DocTemplateHelper.GetApplicableIDTypes().Where(type => type.Value != 0);
IDTypesRepeater.DataBind();
}
}

Handling the checkedchanged event of inner repeater Checkbox control in asp.net nested repeaters

I have nested repeaters on my aspx page.In the outer repeater I am displaying a list of products and in the inner repeater I am displaying a list of additional options associated with each product.The inner repeater contains a checkbox,textbox,label and other stuff.I would like to find the controls inside the outer repeater when a user selects a checkbox in the inner repeater.In order to handle this I am using the following code.
<asp:Repeater ID="OuterRepeater" runat="server"
onitemdatabound="OuterRepeater_ItemDataBound" >
<ItemTemplate>
<asp:Label ID="CodeLabel" runat="server" Text='<%# Eval("Code") %>'></asp:Label>
<asp:Repeater ID="InnerRepeater" runat="server" OnItemCreated="InnerRepeater_ItemCreated">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="true"/>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
......
.......
</ItemTemplate>
</asp:Repeater>
......
......
</ItemTemplate>
</asp:Repeater>
protected void InnerRepeater_ItemCreated(object sender, RepeaterItemEventArgs e)
{
RepeaterItem ri = (RepeaterItem)e.Item;
if (ri.ItemType == ListItemType.Item || ri.ItemType == ListItemType.AlternatingItem
)
{
CheckBox cb = ri.FindControl("CheckBox1") as CheckBox;
cb.CheckedChanged += new EventHandler(CheckBox1_CheckedChanged);
}
}
private void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
CheckBox cb = (CheckBox)sender;
if (cb.Checked)
{
//do something
}
else
{
//do something
}
}
But the checkedChanged event of the checkbox is not firing for some reason.Also I am not sure how to access the textbox of the outer repeater in the checked changed event of the innter repeater checkbox control.
Could someone please help me with this?
Thanks
It does not fire the CheckedChanged event, since you have declared the event handler as private, You have to make it Protected or Public
Protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
You can access the Textbox control like..
private void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
CheckBox checkBox = (CheckBox)sender;
Textbox textbox1 = (TextBox)checkBox.Parent.FindControl("TextBox1");
String textboxText = textbox1.Text;
}
It doesn't look like you defined an event handler in your markup.
<asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="true" OnCheckedChanged="CheckBox1_CheckedChanged" />
Muhammad Akhtar's answer helped me a lot today!
I just needed to set a specific ID to my dynamic generated checkboxes inside my reapeater to recover the origin of the event, and do the rest of the processing, and it worked perfectly.
chkAtivo.ID = DataBinder.Eval(e.Item.DataItem, "id").ToString();
Reovered just as the sample.
Cant vote up yet, but thank you.

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