Function isn't called on onclick event? - c#

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
Width="245px" onselectedindexchanged="GridView1_SelectedIndexChanged" >
<Columns>
<asp:TemplateField>
<ItemStyle BackColor="#CCCCCC" ForeColor="Black" Width="250px" HorizontalAlign="Center" BorderStyle="None" />
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("users") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I don't want to use the auto generated select link or any button, I just want the label (or the link) itself to fire the selectedIndexChanged event.
The C# code is :-
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) {
show_chats();
}
But the event method is not being called. Please suggest what to do

<a onclick="..."> is strictly HTML markup, and the onclick is looking for a javascript function called GridView1_SelectedIndexChanged, not a server side method. Change this to:
<asp:LinkButton runat="server" OnClick="GridView1_SelectedIndexChanged">

If you dont want to use linkbutton, alternatively, you can do as follows-
<asp:Label ID="Label5" runat="server" Text='<%# Bind("users") %>'>
And code behind
protected void Page_Load(object sender, EventArgs e)
{
yourlinkId.ServerClick += new EventHandler(GridView1_SelectedIndexChanged);
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
show_chats();
}

Related

Image button on gridview not triggering asp.net

so i have a gridview with an imagebutton, thing is that it never triggers. I dont know why. here is the code.
<asp:GridView ID="GridView1" runat="server" Width="233px"
OnCommand="GridView1_RowCommand" onrowcommand="GridView1_RowCommand"
DataKeyNames="Nombre">
<Columns>
<asp:TemplateField HeaderText="" ItemStyle-Width="12%" ItemStyle-
HorizontalAlign="Center" >
<ItemTemplate>
<asp:ImageButton ID="lnkEditar" runat="server" CommandName="Edit"
ImageUrl="Imagenes/edit.png" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and the code behind:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
int index = Convert.ToInt32(e.CommandArgument);
Label1.Text = GridView1.Rows[index].Cells[2].ToString();
}
}
I debugged it and it never triggers the RowCommand event. Any help is thanked!
Try to change as follow OnRowCommand
OnRowCommand="GridView1_RowCommand"

RadButton - Single Click approach, not working inside RadGrid EditItemTemplate

There is a RadGrid inside which there is a RadComboBox and asp Button in
EditItemTemplate.
Below is the current code:
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" runat="server" Text='<%# Eval("AccountCode")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<telerik:RadComboBox ID="ddlAccountCode" runat="server" Height="200" Width="240" DropDownWidth="310"
EnableLoadOnDemand="True" OnItemsRequested="ddlAccountCode_ItemsRequested" EnableItemCaching="true"
ShowMoreResultsBox="True" EnableVirtualScrolling="true" AllowCustomText="true" MarkFirstMatch="true"
Filter="Contains" HighlightTemplatedItems="true" CausesValidation="true" AppendDataBoundItems="true"
DataTextField="AccountDescription" DataValueField="AccountCodeID"
ShowDropDownOnTextboxClick="false"
OnClientDropDownOpening="OnClientDropDownOpening" OnClientItemsRequested="OnClientItemsRequested"
OnClientTextChange="LoadECnEntityKeys" />
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClient="btnSearch_Click" />
<asp:Label ID="lblMsg" runat="server" Visible="false"></asp:Label>
</EditItemTemplate>
</telerik:GridTemplateColumn>
protected void btnSearch_Click(object sender, EventArgs e)
{
Response.Write("Default.aspx");
//other code
}
When I type/key-in something inside RadComboBox and click on asp Button,
then only the searching related to key-in text starts and display after execution of OnClick event of asp Button.
Now, the new requirement came to place RadButton(with - Single Click
approach) in place of asp Button, to avoid double click.
Problem is: when I implement RadButton inside EditItemTemplate of RadGrid, RadButton never postback i.e., when I click on it nothing happens.
But same RadButton when I use outside of RadGrid, is working fine.
Below is the code using RadButton(with - Single Click
approach):
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" runat="server" Text='<%# Eval("AccountCode")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<telerik:RadComboBox ID="ddlAccountCode" runat="server" Height="200" Width="240" DropDownWidth="310"
EnableLoadOnDemand="True" OnItemsRequested="ddlAccountCode_ItemsRequested" EnableItemCaching="true"
ShowMoreResultsBox="True" EnableVirtualScrolling="true" AllowCustomText="true" MarkFirstMatch="true"
Filter="Contains" HighlightTemplatedItems="true" CausesValidation="true" AppendDataBoundItems="true"
DataTextField="AccountDescription" DataValueField="AccountCodeID"
ShowDropDownOnTextboxClick="false"
OnClientDropDownOpening="OnClientDropDownOpening" OnClientItemsRequested="OnClientItemsRequested"
OnClientTextChange="LoadECnEntityKeys" />
<telerik:RadButton runat="server" ID="btnSearch" Text="Search" SingleClick="true"
SingleClickText="Submitting..." OnClick="btnSearch_Click" />
<asp:Label ID="lblMsg" runat="server" Visible="false"></asp:Label>
</EditItemTemplate>
</telerik:GridTemplateColumn>
protected void btnSearch_Click(object sender, EventArgs e)
{
Response.Write("Default.aspx");
//other code
}
Please let me know why is this hapenning?
Please do reply
Thanks in advance
I would recommend you to use CommandName as button event. Anyway here is my code... I tried use OnClick and CommandName it work perfectly fine. I suspect your error will be some sort of javascript...
.aspx
<telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="false" Width="100%"
OnNeedDataSource="RadGrid1_NeedDataSource" OnItemCommand="RadGrid1_ItemCommand"
OnItemDataBound="RadGrid1_ItemDataBound">
<MasterTableView EditMode="InPlace">
<Columns>
<telerik:GridTemplateColumn>
<ItemTemplate>
<asp:Label ID="lblAcCode" runat="server" Text='<%# Eval("T")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<telerik:RadComboBox ID="rcb" runat="server" AllowCustomText="true">
</telerik:RadComboBox>
<telerik:RadButton runat="server" ID="btnSearch" Text="Search"
SingleClick="true" SingleClickText="Submitting..." CommandName="Search" />
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn>
<ItemTemplate>
<telerik:RadButton ID="btnEdit" runat="server"
Text="Edit" CommandName="Edit"></telerik:RadButton>
</ItemTemplate>
<EditItemTemplate>
<telerik:RadButton ID="btnCancel" runat="server" Text="Cancel"
CommandName="Cancel"></telerik:RadButton>
</EditItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
.cs
protected void Page_Load(object sender, EventArgs e)
{
// Check
if (!IsPostBack)
{
// Variable
DataTable dt = new DataTable();
dt.Columns.Add("T");
// Loop & Add
for (int i = 0; i < 10; i++)
dt.Rows.Add(i + "");
// Check & Bind
if (dt != null)
{
ViewState["Grid"] = dt;
RadGrid1.DataSource = dt;
RadGrid1.DataBind();
// Dispose
dt.Dispose();
}
}
}
protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
RadGrid1.DataSource = ViewState["Grid"] as DataTable;
}
protected void btnSearch_Click(object sender, EventArgs e)
{
Response.Write("GG");
}
protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
{
// Check
if (e.CommandName == "Search")
{
// Variable
GridEditableItem item = e.Item as GridEditableItem;
string something = "";
// Find Control
RadComboBox rcb = item.FindControl("rcb") as RadComboBox;
// Check
if (rcb != null)
{
// Set
something = rcb.Text;
// Do Something
Response.Write(something);
}
}
}
protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{
// Check
if (e.Item is GridEditableItem)
{
// FindControl
RadComboBox rcb = e.Item.FindControl("rcb") as RadComboBox;
// Check
if (rcb != null)
{
rcb.DataSource = ViewState["Grid"] as DataTable;
rcb.DataTextField = "T";
rcb.DataValueField = "T";
rcb.DataBind();
}
}
}

Keep value after postback updatepanel

I have a textbox which is inside a updatepanel -> detailsview. When I click insert I basically call a method to update DB. Now I'm trying to save the value typed in the textbox in the textbox so I don't lose it.
Shortly I wanna set the textbox value, with the value that is inserted.
My aspx:
<asp:UpdatePanel runat="server" ID="insert" UpdateMode="Conditional">
<ContentTemplate>
<table>
<tr>
<Fields>
<td class="style1">
<asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="500px" AutoGenerateRows="False"
DataKeyNames="strPositionId,nFolderId,tmVaRPosition" DataSourceID="ODSManualPosVaR"
OnItemInserted="DetailsView1_ItemInserted" OnItemInserting="DetailsView1_ItemInserting"
DefaultMode="Insert" SkinID="detailsviewSkin" EnableModelValidation="True">
<asp:TemplateField HeaderText="Name" SortExpression="strPositionName">
<InsertItemTemplate>
<asp:TextBox ID="strPositionName" Width="380px" MaxLength="49" runat="server" Text='<%# Bind("strPositionName") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Width="380px" Text='<%# Bind("strPositionName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</asp:DetailsView>
</td>
</Fields>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
My Page_Load:
protected new void Page_Load(object sender, EventArgs e)
{
base.Page_Load(sender, e);
strSystemId = Request["nSystemId"];
CheckPermission(strSystemId);
if (!IsPostBack || !PageHeader1.SystemId.Equals(strSystemId))
{
RefreshGrid();
DetailsView1.DataBind();
}
}
When click insert:
protected void DetailsView1_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
{
UpdateDB();
//Trying to store the textbox value in a session variable
Session["Test"] = ((TextBox)DetailsView1.FindControl("strPositionName")).Text;
KeepValues();
}
KeepValues:
private void KeepValues()
{
var txtName = (TextBox)DetailsView1.FindControl("strPositionName");
var name = Session["Test"].ToString();
txtName.Text = name;
}
When I debug it stops at KeepValues and the Session variable is working. But I still can't set the textbox.text to it.
Why does this not work? Is it because of a postback? All I want is the value inside strPositionName to be stored in a variable (working) and then set as textbox.text

LinkButton's not firing GridView_RowCommand

I have a LinkButton inside a GridView that passes a CommandArgument and tries to fire RowCommand
GridView declaration:
<asp:GridView PageIndex="0" OnRowCommand="GridView1_RowCommand" PageSize="10" AllowPaging="true" OnPageIndexChanging="GridView1_PageIndexChanging"
ID="GridView1" runat="server" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None"
BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal" Width="700px"
AutoGenerateColumns="False" OnPageIndexChanged="GridView1_PageIndexChanged">
LinkButton inside the GridView:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" OnClientClick="return confirm('Are you sure you want to delete this checklist?');" runat="server" CausesValidation="false" CommandName="DeleteChecklist" CommandArgument='<%# Eval("refID") %>' Text="Delete"></asp:LinkButton>
</ItemTemplate>
<ItemStyle ForeColor="Black" />
<ControlStyle BorderStyle="None" ForeColor="Black" />
</asp:TemplateField>
Code behind:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DeleteChecklist")
{
string refID = e.CommandArgument.ToString();
DAL.DeleteChecklist(refID);
}
}
I placed a breakpoint at RowCommand but it doesn't get fired at all, any idea why?
I assume that you're databinding the GridView on postbacks. So always embed it in a if(!IsPostBack) check:
protected void Page_Load(Object sender, EventArgs e)
{
if(!IsPostBack)
{
GridView1.DataSource = getSource();
GridView1.DataBind();
}
}
Otherwise events won't be triggered and edited values will be overridden.
Another possible reason: Have you disabled ViewState?
EDIT2: Ok it got better. You can make it work with AllowCustomPaging="true" but the property VirtualItemCount must have to be greater than the PageSize value of your grid view. Look at this:
<asp:GridView runat="server" ID="gvPresupuestos" AutoGenerateColumns="False"
OnRowCommand="gvPresupuestos_RowCommand"
OnPageIndexChanging="gvPresupuestos_PageIndexChanging"
OnPreRender="gvPresupuestos_PreRender" ItemType="Core.NominaEntities.TipoPresupuesto"
AllowPaging="true" PageSize="1" AllowCustomPaging="true"
UseAccessibleHeader="true" GridLines="None" CssClass="table table-hover"
ShowHeaderWhenEmpty="True">
<Columns>
<asp:BoundField HeaderText="Nombre del presupuesto" DataField="Nombre" />
<asp:TemplateField HeaderText="Opciones">
<ItemTemplate>
<a href='<%# "Detalle?p=" + Item.IdTipoPresupuesto.ToString() %>'
target="_self"><%# Item.Editable ? "Editar" : "Ver" %></a>
<asp:LinkButton runat="server"
CommandArgument='<%# Item.IdTipoPresupuesto.ToString() %>'
CommandName="Deshabilitar"
Text="Deshabilitar" Visible='<%# !Item.Editable ? true : false %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
FillView() method:
private void FillView(int desiredPage)
{
var cliente = ClientFactory.CreateAuthServiceClient();
using (cliente as IDisposable)
{
// this list only has 1 item.
List<TipoPresupuesto> resultado = cliente.ObtenerTiposDePresupuesto();
gvPresupuestos.DataSource = resultado;
// For testing pursposes, force the virtual item count to 1000.
gvPresupuestos.VirtualItemCount = 1000;
gvPresupuestos.DataBind();
}
}
So, the LinkButton does not fire the gvPresupuestos_RowCommand event unless the virtual item count is greater than the VirtualItemCount property.
I hope this helps.
EDIT1: I found it. You can make it work by changing the value of "AllowCustomPaging" to false. I don't know why, but hope this can help.
ORIGINAL 'ANSWER':
I have the same problem. You can see the my code here:
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<div class="jumbotron jumbotron-small">
<h2>Presupuestos</h2>
</div>
<asp:GridView runat="server" ID="gvPresupuestos"
AutoGenerateColumns="False" AllowPaging="true" AllowCustomPaging="true" PageSize="20"
OnRowCommand="gvPresupuestos_RowCommand"
OnPageIndexChanging="gvPresupuestos_PageIndexChanging"
DataKeyNames="IdTipoPresupuesto" OnPreRender="gvPresupuestos_PreRender"
ItemType="Core.NominaEntities.TipoPresupuesto" ShowHeaderWhenEmpty="True"
UseAccessibleHeader="true" GridLines="None" CssClass="table table-hover">
<Columns>
<asp:BoundField HeaderText="Nombre del presupuesto" DataField="Nombre"/>
<asp:TemplateField HeaderText="Opciones">
<ItemTemplate>
<asp:LinkButton runat="server" Text="Deshabilitar"
Font-Underline="true" CommandName="Deshabilitar"
Visible='<%# Item.Editable ? true : false %>'
CommandArgument='<%# Item.IdTipoPresupuesto %>' />
<a href='<%# "Detalle?p=" + Item.IdTipoPresupuesto.ToString() %>'
target="_self"><%# Item.Editable ? "Editar" : "Ver" %></a>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField ButtonType="Link" CommandName="Deshabilitar"
Text="Deshabilitar (this fires event)" />
</Columns>
</asp:GridView>
<table class="large-table">
<tr>
<td class="text-right">
<a runat="server" class="btn btn-primary" href="Detalle">Nuevo presupuesto</a>
</td>
</tr>
</table>
</asp:Content>
Code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
InitializeControls();
SetPermissions();
FillView(1);
}
}
protected void gvPresupuestos_PreRender(object sender, EventArgs e)
{
// Habilita bootstrap
gvPresupuestos.HeaderRow.TableSection = TableRowSection.TableHeader;
}
protected void gvPresupuestos_RowCommand(object sender, GridViewCommandEventArgs e)
{
// This is never fired by the LinkButton in the ItemTemplate
// But the ButtonField actually fires it.
if (e.CommandName.Equals("Deshabilitar"))
{
// This is how I've been doing it in the whole project but thanks to this
// shit I can't use the CommandArgument of the LinkButton in the ItemTemplate
// Guid idPresupuesto = new Guid(e.CommandArgument.ToString());
// I don't know what I'm supposed to do now.
// ¿Why this only happens in this page?, ¿WTF?
Guid idPresupuesto = gvPresupuestos.GetTheIdFromDataKeysWithFuckingMagic();
var cliente = ClientFactory.CreateServiceClient();
using (cliente as IDisposable)
{
cliente.DeshabilitarPresupuesto(idPresupuesto);
}
}
FillView(1);
}
protected void gvPresupuestos_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvPresupuestos.PageIndex = e.NewPageIndex;
FillView(e.NewPageIndex + 1);
}
#region helper methods
private void InitializeControls()
{
// Not required yet
}
private void FillView(int desiredPage)
{
var cliente = ClientFactory.CreateAuthServiceClient();
using (cliente as IDisposable)
{
var resultado = cliente.ObtenerTiposDePresupuesto();
gvPresupuestos.DataSource = resultado;
gvPresupuestos.DataBind();
}
}
private void SetPermissions()
{
// not required yet
}
#endregion
I've tried enabling and disabling viewstate in the gridview but didn't get different results.
Here is what happens with breakpoints:
You type the url and load the page for the first time.
Then you access the code in the block if(!IsPostBack).
Now you can click both the LinkButton in the ItemTemplate and the ButtonField(Look screenshot)
If you click the LinkButton in the ItemTemplate, it doesn't fire gvPresupuestos_RowCommand. It does a postback, of course. But gvPresupuestos_RowCommand simply doesn't get fired. My code doens't handle that weird postback and the page does the things it would do with a regular postback. After it, you end up with an empty gridview because in the flow of this postback, FillView() is never called.(Look screenshot)
If you click the ButtonField, the event gvPresupuestos_RowCommand is fired, and everything is normal. But I require the IdPresupuesto of the clicked row and I don't know how to get it now.
This is weird. I've implemented this model in all the info pages of the system (there are like 15 modules like this) and never had problems until now.
I had the same problem for a LinkButton in a ListView.
Turns out I should have been using OnItemCommand in the ListView, not OnRowCommand.
Changing this fixed the issue.
Also, you must have a CommandName set on the LinkButton (but no OnCommand).

On button Click in the Grid I can't get in to the function

Using CSharp, I'm not getting into the (GridView1_RowDeleting) function on the button click.. I don't know whats the problem is but wasted alot of time on it.
Default.aspx
asp:GridView ID="GridView1" runat="server" OnRowDeleting="GridView1_RowDeleting"
AllowPaging="True">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="img1" runat="server" CommandName="GridView1_RowDeleting" ImageUrl="~/Images/cross.png" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Default.aspx.cs
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
Use OnItemCommand:
protected void Test(object sender,DataGridEventArgs e)
{
if(e.CommandName == "GridView1_RowDeleting")
{
// do something
}
}
<asp:GridView ID="GridView1" runat="server" OnItemCommand="Test" AllowPaging="True">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="img1"
runat="server"
CommandName="GridView1_RowDeleting"
ImageUrl="~/Images/cross.png" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You have to use the OnCommand property of ImageButton:
Please update your code with following.
Write OnCommand="GridView1_RowDeleting"
I hope it would work.
protected void GridView1_RowDeleting(object sender, CommandEventArgs e)
{
// Do something
}

Categories