PageIndexChanging function not being called when I change page number in gridview - c#

Dear Stack Overflowers,
I have a gridview in the front end page and here it is in asp.net code:
<asp:GridView ID="grdManufact" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#336666" BorderStyle="Double" BorderWidth="3px" CellPadding="4"
GridLines="Horizontal" AllowPaging="True" OnRowDataBound="manufGridView_RowDataBound" EnableModelValidation="False" EnableSortingAndPagingCallbacks="True" HorizontalAlign="Center" OnSelectedIndexChanged="grdManufact_SelectedIndexChanged" OnPageIndexChanging="grdManufact_PageIndexChanging">
<Columns>
<asp:BoundField DataField="SrNo" HeaderText="SrNo" />
<asp:BoundField DataField="Manufacturer" HeaderText="Manufacturer" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:BoundField DataField="isModerated" HeaderText="Approved" />
<asp:BoundField />
Well that is the main part of it but it displays correctly and binds correctly upon page load.
Whenever I change page to page 2 or 3 or whatever of the gridview, my gridview disappears! I have tried putting a breakpoint in the PageIndexChanging function but the breakpoint is not reached which tells me that the event is not even firing and yet the gridview just disappears. Here is my backend function Page Index Changing anyway:
protected void grdManufact_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdManufact.PageIndex = e.NewPageIndex;
BindGrid();
}
And the BindGrid() function used to bind the grid :
public void BindGrid()
{
string strConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString2"].ToString();
SqlConnection conn = new SqlConnection(strConnectionString); // Connect to database
conn.Open(); // Open Connection
string com = "select ManufacturerID as SrNo, ManufacturerName as Manufacturer, ManufacturerDescription as Description,isModerated From VehicleManufacturer";
SqlDataAdapter adpt = new SqlDataAdapter(com, conn); // Select all manufacturers in the table
DataTable dt = new DataTable(); // Create a new Data Table
adpt.Fill(dt); // Fill it with manufacturers
grdManufact.DataSource = dt; // Make the datasource of the manufacturer grid the new table
grdManufact.DataBind(); // Bind data for the grid
conn.Close(); // Close database connection. Disconnect
}
Here is my page load in case you wanted that too:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) // If this is the first time loading the page through postback
BindGrid(); // Bind the Manufacturers to the gridview
else
{
ClientScript.GetPostBackEventReference(this, string.Empty);
if (Request.Form["__EVENTTARGET"] == "Button2_Click")
{
//call the method
btnDelete_Click(this, new EventArgs());
}
}
}
Can you please tell me what I am doing wrong or point me in the right direction to fix this please?

remove EnableSortingAndPagingCallbacks="True" property if you need to excute server side page index changed event or set it false

I remember that this happen if you set EnableViewState = false. Make it EnableViewState = true ! If the grid disappears on every postback just put the binding in if(!IsPostBack) in Page_Load method.

Related

Best way to load data from DB and show in GridView

I am newbie to the ASP.Net world and have a confusion on how to approach the below scenario.
In my application I have to fetch the data from the database when page is loaded and show this in a GridView. The table currently has around 1000 records with about 7 columns. But the data will keep growing.
Here is the code of how I am binding the data to the grid.
protected void Page_Load(object sender, EventArgs e)
{
var data = new AppsAuthData().GetAllUsers();
gridUsersInfo.DataSource = data;
gridUsersInfo.DataBind();
}
I came to know that on every post back above code is getting executed (which obviously is not good). So I added the following to that start of the function
if (IsPostBack)
return;
var data = new AppsAuthData().GetAllUsers();
gridUsersInfo.DataSource = data;
gridUsersInfo.DataBind();
Page Markup
<%# Page Language="C#" AutoEventWireup="true" MasterPageFile="~/Site.Master" CodeBehind="RemoveUsers.aspx.cs" Inherits="AppsAuth.Authencations.RemoveUsers" %>
This again has an issue that after Postbacks, GridView has nothing to show. So next I saved my results to the ViewState and on each post back i was retrieving/updating the ViewState.
But since data can be huge in some scenarios, so what are best options available to deal with such issues?
GridView snippet
<asp:GridView ID="gridUsersInfo" runat="server" Width="100%" ForeColor="#333333" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="false" OnSorting="UserInfo_Sorting" OnRowEditing="gridUsersInfo_RowEditing"
OnPageIndexChanging="gridUsersInfo_PageIndexChanging" AutoGenerateEditButton="True">
> <Columns>
<asp:BoundField DataField="USER_ID" ReadOnly="True" HeaderText="ID" SortExpression="USER_ID" />
<asp:BoundField DataField="USER_NAME" ReadOnly="False" HeaderText="User Name" SortExpression="USER_NAME" />
</Columns>
</asp:GridView>
protected void gridUsersInfo_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gridUsersInfo.PageIndex = e.NewPageIndex;
gridUsersInfo.DataBind();
}
Instead of putting everything on PageLoad. You can put a button and write the code to populate GridView in the click event of that button.
Using the asp.net control Gridview with pagination enabled will do this for you.
Check the following example:
HTML
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowPaging="true"
OnPageIndexChanging="OnPageIndexChanging" PageSize="10">
<Columns>
<asp:BoundField ItemStyle-Width="150px" DataField="CustomerID" HeaderText="Customer ID" />
<asp:BoundField ItemStyle-Width="150px" DataField="ContactName" HeaderText="Contact Name" />
<asp:BoundField ItemStyle-Width="150px" DataField="City" HeaderText="City" />
<asp:BoundField ItemStyle-Width="150px" DataField="Country" HeaderText="Country" />
</Columns>
</asp:GridView>
CodeBehind
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT CustomerId, ContactName, City, Country FROM Customers"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
Implementing Pagination
The event handler is called when the page is changed inside the GridView.
The value of the PageIndex of the Page which was clicked is present inside the NewPageIndex property of the GridViewPageEventArgs object and it is set to the PageIndex property of the GridView and the GridView is again populated by calling the BindGrid function.
protected void OnPaging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
Source : http://www.aspsnippets.com/Articles/Paging-in-ASPNet-GridView-Example.aspx
What you have to do is just bind bind gridview when !IsPostback in page_load
if(!IsPostBack)
{ var data = new AppsAuthData().GetAllUsers();
ViewState["UserData"] = data;
gridUsersInfo.DataSource = data;
gridUsersInfo.DataBind();
}
Hear is an example : Asp.Net Bind Grid View
In .aspx file
<form runat="server" onload="Page_Load">
<asp:GridView runat="server" ID="gridEvent" AutoGenerateColumns="False" BackColor="White"
BorderStyle="None" BorderWidth="0px" class="table mb-0"
>
<RowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="EventId" HeaderText="#" />
<asp:BoundField DataField="Title" HeaderText="Event Title" />
<asp:BoundField DataField="EventDate" HeaderText="Event Date" />
<asp:BoundField DataField="Location" HeaderText="Venue" />
<asp:BoundField DataField="RegisteredUsers" HeaderText="Registred User(s)" />
<asp:CommandField ShowEditButton="True" />
<asp:CommandField ShowDeleteButton="True" />
</Columns>
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<HeaderStyle BackColor="#FBFBFB" Font-Bold="True" ForeColor="#5A6169" />
</asp:GridView>
</form>
in the .aspx.designer.cs
public partial class Default
{
/// <summary>
/// txtLocation control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.GridView gridEvent;
}
in the .aspx.cs file
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
// Enable the GridView paging option and
// specify the page size.
gridEvent.AllowPaging = true;
gridEvent.PageSize = 15;
// Initialize the sorting expression.
ViewState["SortExpression"] = "EventId ASC";
// Enable the GridView sorting option.
gridEvent.AllowSorting = true;
BindGrid();
}
}
private void BindGrid()
{
// Get the connection string from Web.config.
// When we use Using statement,
// we don't need to explicitly dispose the object in the code,
// the using statement takes care of it.
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlConn"].ToString()))
{
// Create a DataSet object.
DataSet dsPerson = new DataSet();
// Create a SELECT query.
string strSelectCmd = "SELECT * FROM EventsList";
// Create a SqlDataAdapter object
// SqlDataAdapter represents a set of data commands and a
// database connection that are used to fill the DataSet and
// update a SQL Server database.
SqlDataAdapter da = new SqlDataAdapter(strSelectCmd, conn);
// Open the connection
conn.Open();
// Fill the DataTable named "Person" in DataSet with the rows
// returned by the query.new n
da.Fill(dsPerson, "EventsList");
// Get the DataView from Person DataTable.
DataView dvPerson = dsPerson.Tables["EventsList"].DefaultView;
// Set the sort column and sort order.
dvPerson.Sort = ViewState["SortExpression"].ToString();
// Bind the GridView control.
gridEvent.DataSource = dvPerson;
gridEvent.DataBind();
}
}
//Implementing Pagination
protected void OnPaging(object sender, GridViewPageEventArgs e)
{
gridEvent.PageIndex = e.NewPageIndex;
gridEvent.DataBind();
}

unable to update gridview values in .net

while updating gridview record . old values only getting updated. im using bound field. getting old value while im fetching data in variable.
<asp:GridView runat="server" ID="GvLeads" AutoGenerateColumns="false" AutoGenerateEditButton="true" AutoGenerateDeleteButton="true" OnRowDeleting="GvLeads_RowDeleting" OnRowEditing="GvLeads_RowEditing" OnRowCancelingEdit="GvLeads_RowCancelingEdit" EmptyDataText="No Records Found" OnRowUpdating="GvLeads_RowUpdating" OnRowDeleted="GvLeads_RowDeleted">
<Columns>
<asp:BoundField HeaderText="Id" DataField="LeadId" />
<asp:BoundField HeaderText="Company" DataField="Companyname" />
</Columns>
</GridView >
code behind
protected void GvLeads_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GvLeads.Rows[e.RowIndex];
String str = ((TextBox)(row.Cells[1].Controls[0])).Text;
int Leadid = Convert.ToInt32(str);
string CompanyName = ((TextBox)(row.Cells[2].Controls[0])).Text;
}
This usually happens when you are populating grid at Page_Load as soon as RowUpdating event gets called before that Page_Load event get's called which populates the grid with initial values. How to Avoid? Use !IsPostBack for this purpose
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid(); // For e.g.
}
}

asp.net gridview edit mode index

I have a gridview which is populated via a sql data source with the SELECT command: Select * FROM myTable
When the page is first loaded that displays every record in the table.
The gridview has an Edit button for each row and when the user clicks the row I want to update the gridview to display only that result in the gridview so I change the SELECT command of the sql data source to SELECT * FROM myTable WHERE ID = currentEditRow
That works except for one issue, when editing any other row but the first, the Update and Cancel buttons do not show up on the row. It is like is not in edit mode.
Any idea why that is?
Code:
protected void gvResults_RowEditing(object sender, GridViewEditEventArgs e)
{
gvResults.EditIndex = e.NewEditIndex;
SqlDataSource1.SelectCommand = "SELECT * FROM [myTable] WHERE ID = '" + ID + "'";
}
GridView will bind data again automatically when you set a new command to SqlDataSource1.SelectCommand. This made it returns to start mode (Display read-only data with Edit button in GridView).
Otherwise, you trick it as my sample code below ...
This is my GridView binding data with SqlDataSource1, has DataKey names "code". There are three event handlings to implement: OnRowEditing, OnSelectedIndexChanged and OnRowCancelingEdit.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1"
DataKeyNames="code"
OnRowEditing="GridView1_RowEditing"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
OnRowCancelingEdit="GridView1_RowCancelingEdit">
<Columns>
<asp:BoundField DataField="std_room_id" HeaderText="Room ID" SortExpression="std_room_id" />
<asp:BoundField DataField="booking_name" HeaderText="Name" SortExpression="booking_name" />
<asp:BoundField DataField="course_id" HeaderText="Course" SortExpression="course_id" />
<asp:BoundField DataField="course_period" HeaderText="Period" SortExpression="course_period" />
<asp:BoundField DataField="start_date" HeaderText="Start Date" SortExpression="start_date" />
<asp:BoundField DataField="end_date" HeaderText="End Date" SortExpression="end_date" />
<asp:CheckBoxField DataField="approved" HeaderText="Approved" SortExpression="approved" />
<asp:CommandField ShowSelectButton="true" SelectText="Edit"/>
<asp:CommandField ShowEditButton="true" Visible="false"/>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
SelectCommand="SELECT * FROM [BookingRoom]"></asp:SqlDataSource>
</div>
I have two CommandFields: SelectButton to click when user want open Edit Mode, and the second CommandField for display Update and Cancel buttons.
And this is my code-behide
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.Columns[7].Visible = false;
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
string code = GridView1.DataKeys[GridView1.SelectedIndex].Value.ToString();
SqlDataSource1.SelectCommand = "SELECT * FROM [BookingRoom] WHERE code = '" + code + "'";
GridView1.Columns[8].Visible = true;
GridView1.SetEditRow(0);
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.Columns[7].Visible = true;
GridView1.Columns[8].Visible = false;
}
I tricked it by show the SelectButton (display text as "Edit") in GridView with all loaded data in start mode. When user selects the row by clicking the SelectButton, it will start to do the steps in GridView1_SelectedIndexChanged which try to display only the selected row in GridView and set Edit Mode to that row togather with displaying the second CommandField (Update and Cancel buttons).
To set Edit Mode by this line GridView1.SetEditRow(0);, it will do the step in GridView1_RowEditing which try to hide the SelectButton.
Final, you have to handle the cancling Edit Mode as in GridView1_RowCancelingEdit which try to display the SelectButton, and hide the Update and Cancel buttons.
I access those two CommandFields by their column index according to my columns in GridView: column index of Select button is 7 and column index of Update and Cancel buttons is 8
Try to interchange the two line of codes:
protected void gvResults_RowEditing(object sender, GridViewEditEventArgs e)
{
SqlDataSource1.SelectCommand = "SELECT * FROM [myTable] WHERE ID = '" + ID + "'";
gvResults.EditIndex = e.NewEditIndex;
}

Gridview Button in TemplateField only fires on second click

I've done some searching prior to asking, and although this post is close, it doesn't work for my scenario.
What I find is that the "delete" button in my template field seems to fire, but the click event does not trigger. Yet the second time you click the button it works as expected.
So, breaking the code down, I am binding my data to a GridView, using a `SqlDataSource.
My page load event starts as follows:
if (!Page.IsPostBack)
{
externalUserDataSource.ConnectionString = "some connection string";
}
My data source is as follows:
<asp:SqlDataSource ID="externalUserDataSource" runat="server"
ConflictDetection="CompareAllValues" SelectCommand="uspGetExternalUsersByTeam"
SelectCommandType="StoredProcedure" ProviderName="System.Data.SqlClient">
<SelectParameters>
<asp:SessionParameter Name="TeamID" SessionField="TeamID" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
And this is my GridView markup:
<asp:GridView ID="gridView" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px"
CellPadding="4" DataKeyNames="LoginID" DataSourceID="externalUserDataSource"
EnableModelValidation="True" OnRowDataBound="GridViewRowDataBound" TabIndex="3">
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="White" />
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
<RowStyle BackColor="LightGoldenrodYellow" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<Columns>
<asp:BoundField DataField="RowID" HeaderText="Row ID" ReadOnly="True"
SortExpression="RowID" Visible="False" />
<asp:BoundField DataField="LoginID" HeaderText="Login ID" ReadOnly="True"
SortExpression="LoginID" Visible="False" />
<asp:BoundField DataField="EmailAddress" HeaderText="Email Address"
ItemStyle-VerticalAlign="Bottom" ReadOnly="True" SortExpression="AssociateName"/>
<asp:BoundField DataField="TeamID" HeaderText="Team ID" ReadOnly="True"
SortExpression="TeamID" Visible="False" />
<asp:CheckBoxField DataField="HasFIAccess"
HeaderText="Has Access to<br />Funding<br/>Illustrator"
ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Bottom"
ReadOnly="True"/>
<asp:CheckBoxField DataField="HasALTAccess"
HeaderText="Has Access to<br />Asset Liability<br/>Tracker"
ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Bottom"
ReadOnly="True"/>
<asp:CheckBoxField DataField="HasFIAAccess"
HeaderText="Has Access to<br />Funding<br/>Illustrator App"
ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Bottom"
ReadOnly="True"/>
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" CssClass="additionsRow" ID="btnDeleteExternalUser" OnClick="DeleteExtUserButtonClick"
CausesValidation="False" Text="Delete"
CommandArgument='<%#Eval("TeamID") + "," + Eval("LoginID") + "," + Eval("EmailAddress") + "," + Eval("HasALTAccess")%>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
So, you can see that I am passing across some information in the button that is used in the event to ensure the correct data is deleted (which is why I cannot use the ButtonField, as suggested in the link above).
The last part to the puzzle is the GridView's databound event:
protected void GridViewRowDataBound(object sender,
GridViewRowEventArgs e)
{
// if rowtype is not data row...
if (e.Row.RowType != DataControlRowType.DataRow)
{
// exit with no further processing...
return;
}
// get the ID for the selected record...
var selectedId = DataBinder.Eval(e.Row.DataItem, "RowID").ToString();
// create unique row ID...
e.Row.ID = string.Format("ExtUserRow{0}", selectedId);
// find the button delete for the selected row...
var deleteButton = (Button)e.Row.FindControl("btnDeleteExtUser");
// get the email address for the selected record...
var selectedUser = DataBinder.Eval(e.Row.DataItem, "EmailAddress").ToString();
// define the message text...
var messageText = string.Format("OK to delete {0}?",
selectedUser.Replace("'", "\\'"));
// add attribute to row delete action...
this.AddConfirmMessage(deleteButton, messageText);
}
Where AddConfirmMessage simply assigns an onclick attribute to the control to ensure the user has to confirm the deletion.
Now, in every case the message pops up 'OK to delete abc#xyz.com?', but as stated earlier, the event assigned to the "delete" button does not trigger until the button is clicked a second time.
Strangely enough, I took this code from another page and modified accordingly, though it doesn't have this issue there:
protected void DeleteExtUserButtonClick(object sender,
EventArgs e)
{
// get the buton which was clicked...
var button = (Button)sender;
// break the delimited array up...
string[] argumentArray = button.CommandArgument.Split(',');
// store the items from the array...
string teamId = argumentArray[0];
string loginId = argumentArray[1];
string emailAddress = argumentArray[2];
string hasAltAccess = argumentArray[3];
using (var conn = new SqlConnection(Utils.GetConnectionString()))
{
// create database command...
using (var cmd = new SqlCommand())
{
// set the command type...
cmd.CommandType = CommandType.StoredProcedure;
// set the name of the stored procedure to call...
cmd.CommandText = "uspDeleteExternalUser";
// create and add parameter to the collection...
cmd.Parameters.Add(new SqlParameter("#TeamId", SqlDbType.Int));
// assign the search value to the parameter...
cmd.Parameters["#TeamId"].Value = teamId;
// create and add parameter to the collection...
cmd.Parameters.Add(new SqlParameter("#LoginId", SqlDbType.VarChar, 50));
// assign the search value to the parameter...
cmd.Parameters["#LoginId"].Value = loginId;
// set the command connection...
cmd.Connection = conn;
// open the connection...
conn.Open();
// perform deletion of user...
cmd.ExecuteNonQuery();
}
}
// bind control to refresh content...
ExtUsersGrid.DataBind();
}
Have I missed something obvious? I am happy to modify if there are better ways to do this.
Edit 1: Following on from the discussions below, I have modified the following:
Removed the Onclick event property of the ButtonItem;
Set the CommandName and CommandArgument as suggested below, and updated the DataKeyNames to use RowID which is a unique ID from the data;
Assigned a RowCommand event for the GridView;
Assigned the delete code to the RowCommand event.
Following these changes, it still fires the row event code on the second click.
Edit 2: FYI - I've now removed the SqlDataSource and the associated code/references, and created a procedure to fill the dataset, which is called on Page_Load (inside the !Page.IsPostBack brackets). I started making the changes below to use the RowCommand event, but they still caused the same issue (i.e. the button will only fire on the second click). As using RowCommand meant converting the BoundFields to ItemTemplates, I reverted back to the button click event as it seemed pointless making all those changes for no gain. If anyone else can help me understand why it only triggers on the second click, would appreciate your input.
OK, frustratingly this was due to some code that for reasons still unknown, works elsewhere.
In the DataBound event, there was two lines of code:
// get the associate name for the selected record...
var selectedId = DataBinder.Eval(e.Row.DataItem, "RowID").ToString();
// create unique row ID...
e.Row.ID = string.Format("ExtUserRow{0}", selectedId);
The process of applying an ID to the rows programatically seems to break the connection between the data and the events.
By removing these two lines of code, it works as expected.
Well instead you can do something like this.
Add a CommandName property to your GridView like this. Also note the changes in the CommandArgument property:
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" CssClass="additionsRow" ID="btnDeleteExtUser"
CausesValidation="False" Text="Delete"
CommandName="OnDelete"
CommandArgument='<%# Container.DisplayIndex %>" '
</ItemTemplate>
</asp:TemplateField>
Code behind will look something like this. Note that I am using the RowCommand event of Gridview.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName == "OnDelete")
{
int rowIndex = Convert.ToInt32(e.CommandArgument);
// now you got the rowindex, write your deleting logic here.
int ID = Convert.ToInt32(myGrid.DataKeys[rowIndex]["ID"].Value);
// id will return you the id of the row you want to delete
TextBox tb = (TextBox)GridView1.Rows[rowIndex].FindControl("textboxid");
string text = tb.Text;
// This way you can find and fetch the properties of controls inside a `GridView`. Just that it should be within `ItemTemplate`.
}
}
Note: mention DataKeyNames="ID" inside your GridView. The "ID" is the primary key column of your table.
Are you binding the GridView on pageload? If so, then move it to !IsPostBack block as show below:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.DataSource = yourDataSource;
GridView1.DataBind();
}
}

Unable to Fire onItemCommand event

I am unable to guess the issue here , as the event of grid item command is not executing .I also changes the pageevent validation state but of no use.
I am pasting .aspx code as well as
The grid is binded perfectly
<telerik:RadGrid ID="frds" runat="server" OnItemCommand="go_frd" AutoGenerateColumns="false" >
<MasterTableView>
<Columns>
<telerik:GridTemplateColumn>
<ItemTemplate>
<asp:Button ID="bt" runat="server" CommandArgument='<%#Eval("frd_ID") %>' Text="test" />
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
The event is this
protected void go_frd(object o, GridCommandEventArgs e)
{
if (e.CommandName == "frd_go")
{
Response.Redirect("Profiling.aspx?uid=" + e.CommandArgument);
}
if (e.CommandName == "add_frd")
{
db_accessDataContext db = new db_accessDataContext();
Frd_request req = new Frd_request();
db.AddFriend(Int64.Parse(cur_mem_id), Int64.Parse(e.CommandArgument.ToString()));
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("dbo.addFriend", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(#"memID", Int64.Parse(cur_mem_id));
cmd.Parameters.Add(#"frdID", Int64.Parse(e.CommandArgument.ToString()));
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex) { }
}
}
I tried many approaches but unable to fire the event for button in grid
I checked it by putting a break point as well ,the trouble is it don't even start execution of the event
Binding COde
string query = "my query containing the frd_id ,works fine in query builder and it also is shown grid view ";
try { SqlConnection con = new SqlConnection(connectionString);
SqlDataAdapter adapter = new SqlDataAdapter(query, con);
adapter.Fill(d0); con.Close();
} catch (Exception ex) { }
frds.DataSource = d0;
frds.DataBind();
You need to set the CommandName:
<asp:Button ID="bt" runat="server"
CommandName="frd_go"
CommandArgument='<%#Eval("frd_ID") %>' Text="test" />
I had a similar issue today.
In my radgrid I had the code to build the sql and populate the radgrid in the page_load event, but I forgot to add
if (!IsPostBack) { }
around this code, so on every page load the grid was being rebuilt and the onitemcommand method was not working. The page seemed to be was posting back on button click or rowclick, but the event was just not firing. Try adding the if (!isPostback) code around your databinding and you might find it works for you.
You will need to set EnablePostBackOnRowClick property to true for ClientSettings. However this will cause a full post back.
.
.
.
</MasterTableView>
<ClientSettings EnablePostBackOnRowClick="true">
</ClientSettings>
</telerik:RadGrid>
You may want to check this thread on Telerik forums

Categories