asp .net button column command - c#

I have the following code on an asp .net project which has a Gridview with the following code:
<Columns>
<asp:ButtonField ButtonType="Button" CommandName="Sel" Text="Select" />
</Columns>
And i am trying to raise an event when it is clicked. I am using the following code in the .cs file:
protected void grdTimes_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Sel")
{
lblError.Text = "command";
}
}
Unfortunately the lblerror.text doesnt changes when a button is clicked. Any ideas?

Well, in my case it worked properly ( I used Response.Write too). I'd tell you to try with Response.Write, and if it works it may be some wrong set up of your label.
If you want to edit your question with your whole markup, feel free to do it!

Related

UpdateButton_Click in form view

I Have a page(manage-darkhast-maghale.aspx) that include a gridview and sqldatasourse.one of the gridview columns is a hyperlink that on click redirects users to (pasokhmaghale.aspx?darkhastMaghaleId={0})
in second page there is a formview and sqldatasourse. after double click on update button on edit template on code behind I have typed below codes to redirect user to first page.
protected void UpdateButton_Click(object sender, EventArgs e)
{
Response.Redirect("manage-darkhast-maghale.aspx");
}
but, after running site and clicking on update button only the page begin redirect and the data has no change on gridview and database. anyone can help me please?
Without seeing the code it is very hard to say. From the information you have provided I would say that you need to leave the CommandName attribute on your Update button in the EditItemTemplate i.e.
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="Update" />
I would add the following event to your FormView that will execute when the record has been updated:
<asp:FormView ID="FormView1" runat="server" OnItemUpdated="FormView1_ItemUpdated"...
In your code behind for the FormView you should have the following:
protected void FormView1_ItemUpdated(object sender, System.Web.UI.WebControls.FormViewUpdatedEventArgs e)
{
if (e.Exception == null && e.AffectedRows > 0)
{
Response.Redirect("manage-darkhast-maghale.aspx");
}
}

Page losing formatting

On my page a I have a few textboxes, AJAX tabpanel and a gridview.
In the Page_Load event, textboxes are filled in; gridview is populated and so on.
My gridview has a button:
<Columns>
<ItemTemplate>
<asp:Button ID="btnRedirect"
Text="Click me"
CommandArgument='<%#Eval("BkId_ZW")%>'
OnClick="DoRedirect"
runat="server" />
</ItemTemplate>
...
</Columns>
and the code behind it looks like:
protected void DoRedirect(object sender, EventArgs e)
{
Button theButton = sender as Button;
string url ="http://../profile/" + theButton.CommandArgument;
Response.Write("<script>window.open('" + url + "');</script>");
}
After button is pressed a new window is open (everything works as expected) but the main page loose values and formatting of the textboxes.
What is going on? How to fix it?
Response.Write() is not favored for this purpose. Since you are adding to the response in the middle of the ASP.net page lifecycle, you are changing the page output. If you view source, you might find your <script>window.open...</script> line in some awkward place.
Therefore, use Page.ClientScript.RegisterStartUpScript() instead.

Change asp:Label text from C# code behind

I've been trying with this for an hour or so; just can't seem to figure out.
I have an asp:Button on an aspx page, required to complete a couple of functions, one of which is to change the text of an asp:Label. This seems like it should be simple and other online posts indicate that I'm approaching the problem correctly but...
The problem is simple but it's killing me. In an effort to debug/troubleshoot, I've stripped the code right back to very basics:
protected void Page_Load(object sender, EventArgs e)
{
allValidationMsg.Text = "Original text";
}
protected void btnRegister_Click(object sender, EventArgs e)
{
allValidationMsg.Text = "Text changed";
}
When the button is clicked, nothing happens. I'm sure it's something simple that I'm missing.
Update:
<asp:Label id="allValidationMsg" runat="server" height="22px" ForeColor="Red"></asp:Label>
<asp:Button class="navbutton" ID="btnRegister" runat="server"
Text="Register User" OnClick="btnRegister_Click" />
I think when you click on the Button, Page_Load is called again and the original text remains. Try this
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
allValidationMsg.Text = "Original text";
}
Apart from this, I assume you register the event handler for the button in the Markup as I cannot see it anywhere in your code-behind
<asp:Button id="Button1" runat="server" OnClick="btnRegister_Click" />
Possibly you have forgotten to bind button click to the handler.
You could do it something like that in code-behind:
mybutton.Click+=btnRegister_Click;
Or in aspx:
<asp:Button id="Button1"
Text="Click here for greeting..."
OnClick="btnRegister_Click"
runat="server"/>
Solved; the problem appears to have been with the use of a CompareValidator. Don't really understand why but when this validator is commented out, problem solved. Funnily enough, RequiredField and RegularExpression validators on same page cause no issues..
Hey I think I know what it is. In your markup does your label look like this??
<asp:Label ID="Label1" runat="server" >Some text</asp:Label>
You want this in your markup:
<asp:Label ID="Lable1" runat="server" text ="some text"></asp:Label>
I have had this happen before. If you change the markup to that. It should work.
I can see that you wrote "onclick" instead of "OnClick" in the markup (case). Possibly it is the cause of the issue.
UPDATE1
Could you try to do so (check if postback works):
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
allValidationMsg.Text = "Original text";
}
else
{
allValidationMsg.Text = "After postback";
}
}
If the text is changing after pressing the button?
UPDATE2 Also, please try to make some changes in the text to understand if a new version really deploys (to exclude strong caching issues).
UPDATE3 You can try to do binding in codebehind (and delete it from aspx).

Event not firing after setting OnClientClick in RowDataBound

I have an Asp.net GridView (populate with a data binding).
One of my columns is a ButtonField (obviously with his own CommandName).
The GridView_RowCommand works perfectly, but if i add a GridView_RowDataBound (in which I simply add a javascript confirm) the GridView_RowCommand event is not fired in the PostBack.
What could be the problem/solution?
Adding code for better understanding:
Aspx code:
<asp:GridView ID="GridView1" runat="server"
OnRowCommand="GridView1_RowCommand"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="MyField1" HeaderText="MyField1" />
<asp:BoundField DataField="MyField2" HeaderText="MyField2" />
<asp:ButtonField Text="MyAction" ButtonType="Image" ImageUrl="myaction.gif" CommandName="myaction" />
</Columns>
</asp:GridView>
c# code:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
(e.Row.Cells[e.Row.Cells.Count - 1].Controls[0] as ImageButton).OnClientClick = "javascript:return confirm (\"Do action?\");";
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "myaction")
{
DoMyAction();
}
}
EDIT:
I forgot to tell that my GridView is inside an ajax TabContainer (AjaxControlToolkit)
this is what is emitted normally for the Image button:
<input type="image" src="myaction.gif" alt="MyAction" onclick="javascript:__doPostBack('GridView1','myaction$1')" style="border-width:0px;" />
when you set OnClientClick in your code-behind, it will prepend your code but still add the __doPostBack function call, resulting in the following html:
<input type="image" src="myaction.gif" alt="MyAction" onclick="javascript:return confirm('Do action?');javascript:__doPostBack('GridView1','myaction$1')" style="border-width:0px;" />
the onclick event handler will return before it gets a chance to do the postback properly (it will just submit the form).
Doing this:
(e.Row.Cells[e.Row.Cells.Count - 1].Controls[0] as ImageButton).OnClientClick = "if (!confirm('Do action?')) { return false; }";
should allow the client-side click event to run the __doPostBack function and raise the RowCommand event server-side as expected when the user clicks OK.
(As a side-note, this is a good example of one of the drawbacks of ASP.NET WebForms - there is a lot of html being generated that you just have no control over. ASP.NET MVC FTW!)
At first glance this seems fine. Have you tried running your code outside the TabContainer?
It might get you in the right direction.
Use sender as argument on ClientScript.GetPostBackClientHyperlink function so it will create client js event dinamicaly. Bellow the example in RowDataBound, where sender is GridView (VB).
YourCommand will be passed as argument for RowCommand event to be raised.
e.Row.Cells(columnIndex).Attributes.Add("onclick", ClientScript.GetPostBackClientHyperlink(sender, "YourCommand$" & e.Row.DataItemIndex))

DetailsView FindControl() returns null after some postbacks

I've been working for a long time with GridViews and DetailsViews, but yesterday I've come across a new scenario, which I quite do not understand.
I have a GridView with ImageButton (CommandName="Insert") which will change the mode of the DetailsView to Insert. Afterwards I'll look for a DropDownList inside that DetailsView and add some items dynamically. Works fine, but one first the first time I press that ImageButton. If I click on "Cancel" in the DetailsView and press the ImageButton again, the .FindControl() Method returns null. What life cycle problem am I facing here?
I've created this sample: (To make it run in your Visual Studio, just bind a DataSource to the DetailsView, otherwise it will not be rendered)
Markup:
<asp:GridView ID="gvCategory" runat="server" OnRowCommand="gvCategory_RowCommand">
<Columns>
</Columns>
<EmptyDataTemplate>
<asp:ImageButton ImageUrl="~/images/add.png" ID="ibAdd" runat="server" CommandName="Insert" />
</EmptyDataTemplate>
</asp:GridView>
<asp:DetailsView ID="dvCategory" runat="server" Width="150px" AutoGenerateRows="false"
AutoGenerateInsertButton="True" DataSourceID="LinqDataSource1">
<Fields>
<asp:TemplateField HeaderText="foo">
<InsertItemTemplate>
<asp:DropDownList ID="ddlCategory" runat="server" Width="150"></asp:DropDownList>
</InsertItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView><asp:LinqDataSource ID="LinqDataSource1" runat="server"
ContextTypeName="WebApplication1.DataClasses1DataContext"
TableName="Categories"></asp:LinqDataSource>
Codebehind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.gvCategory.DataBind();
}
}
protected void gvCategory_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Insert")
{
this.dvCategory.ChangeMode(DetailsViewMode.Insert);
DropDownList _ddlCat = (DropDownList)this.dvCategory.FindControl("ddlCategory");
if (_ddlCat != null)
{
_ddlCat.Items.Clear();
_ddlCat.Items.Add(new ListItem() { Text = "-- empty --", Value = "-1" });
}
}
}
I have also tried using a ItemTemplate, and not a InsertItemTemplate, but this results in the same. After using the ChangeMode-Method the DetailsView.CurrentMode == InsertMode. The only thing I can think of is, that the markup is already generated for the ItemTemplate and changing the Mode to InsertMode can't affect the rendered markup, or something like this.
Does anybody have a solution to this? =)
I think you are on the right track. It's hard to tell without seeing all of the code, but basically any time you change the rendering mode of a row in a repeater-type control you need to rebind it so that it's re-rendered. The fact that FindControl is returning NULL means only one thing: THE CONTROL IS NOT THERE. Which means it was not rendered. You can verify this by looking at the control hierarchy.
So, in your handler for Cancel are you rebinding?

Categories