ASP.NET c# Gridview OnRowUpdating not working - c#

I'm working in Visual Studio 2015.
When the Gridview loads, I can click on "Edit".
When I click Cancel I'm just getting back to the Gridview.
So that good, but if I click "Update" he is doing the same thing as what is happening at "Cancel". No errors.
Here is the method for the OnRowUpdating :
protected void UpdateHandleiding(object sender, GridViewUpdateEventArgs e)
{
SqlConnection Sqlconnection1 = new SqlConnection();
Sqlconnection1.ConnectionString = (System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
//string ID = ((Label)GridView1.Rows[e.RowIndex].FindControl("lblID")).Text;
//string Naam = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtNaam")).Text;
//string URL = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtURL")).Text;
GridViewRow row = GridView1.Rows[e.RowIndex];
int ID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
string Naam = (row.Cells[1].Controls[0] as TextBox).Text;
string URL = (row.Cells[2].Controls[0] as TextBox).Text;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand("UPDATE Handleidingen SET Naam=#Naam, URL=#URL WHERE ID=#ID"))
{
cmd.Parameters.AddWithValue("#ID", ID);
cmd.Parameters.AddWithValue("#Naam", Naam);
cmd.Parameters.AddWithValue("#URL", URL);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
GridView1.EditIndex = -1;
GridView1.DataBind();
}
Here is my OnRowEditing & OnRowCancelingEdit which do work :
protected void EditHandleiding(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
ShowHandleidingen();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
ShowHandleidingen();
}
Here is my Gridview :
<asp:GridView ID="GridView1" runat="server" CssClass="grid-center" AutoGenerateColumns="False"
DataKeyNames="ID" EnableModelValidation="True" OnRowDeleting="GridView1_RowDeleting"
OnRowEditing="EditHandleiding" OnRowUpdating="UpdateHandleiding" OnRowCancelingEdit="CancelEdit">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Naam" HeaderText="Naam"/>
<asp:BoundField DataField="URL" HeaderText="URL"/>
<asp:CommandField ShowEditButton="True" />
<asp:CommandField ShowDeleteButton="true" />
</Columns>
</asp:GridView>

this is simple situation caused by the post back events in asp.net, in the Update Method the page is reloaded from the begining, even if you give new values to the data that you want too submit in the database, asp.net will take the one in the page_load method, when you fill the database in the first place at the page_load method add this condition :
private void Page_Load()
{
if (!IsPostBack)
{
// Fill up the gridView with the data that you want
}
}

protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
}
replace object sender, GridViewUpdateEventArgs e
to
object sender, GridViewRowEventArgs e

Simply change gridview in aspx page
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound">
and then put
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{}

Related

Deleting record from gridview in ASP.NET application

I have the below gridview on a page to display users with a role of "Reviewer". The grid pulls up the records correctly. On the gridview is a "delete" button to remove the Reviewer role. The stored procedure that is called is working correctly when ran manually, but I seem to be missing something on the aspx or codebehind page as while no error is returned, no record is deleted either.
aspx control for gridview:
<asp:GridView ID="GridView1" runat="server" Caption="Current Reviewers" AllowSorting="True" PagerSettings-Mode="NumericFirstLast" OnPageIndexChanging="GridView1_PageIndexChanging"
CaptionAlign="Top" EmptyDataText="No Reviewers Configured." PageSize="10" AllowPaging="true" PagerStyle-HorizontalAlign="Center" PagerStyle-Font-Size="Large"
AutoGenerateColumns="false" AlternatingRowStyle-BackColor="#cccccc" DataKeyNames="UserId" OnRowDeleting="DeleteRecord">
<Columns>
<asp:BoundField DataField="UserId" HeaderText="Id" ItemStyle-Width="300" />
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="250" />
<asp:TemplateField HeaderText="Delete?">
<ItemTemplate>
<span onclick="return confirm('Are you sure to Delete the record?')">
<asp:LinkButton ID="lnkB" runat="Server" Text="Delete" CommandArgument='<%# Eval("UserId") %>' CommandName="DeleteRecord"></asp:LinkButton>
</span>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Updated with full code behind:
namespace cs1.Admin
{
public partial class ReviewerMaintenance : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDownList1();
}
}
private void BindDropDownList1()
{
string connectionString = WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
string selectSQL = String.Format("SELECT Id as UserId, FirstName + ' ' + LastName As Name from AspNetUsers where Id in(SELECT UserId from AspNetUserRoles where RoleId = 1)");
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds, "Reviewer");
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindDropDownList1(); //bindgridview will get the data source and bind it again
}
protected void DeleteRecord(object sender, GridViewDeleteEventArgs e)
{
string UserId = GridView1.DataKeys[e.RowIndex].Value.ToString();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString());
SqlCommand dCmd = new SqlCommand();
{
conn.Open();
dCmd.CommandText = "Reviewer_Delete";
dCmd.CommandType = CommandType.StoredProcedure;
dCmd.Parameters.Add("#UserId", SqlDbType.NVarChar).Value = UserId;
dCmd.Connection = conn;
dCmd.ExecuteNonQuery();
// Refresh the data
BindDropDownList1();
dCmd.Dispose();
conn.Close();
conn.Dispose();
}
}
}
}
Try to use the OnRowCommand event of the GridView to handle this.
In your Gridview markup:
ensure OnRowCommand="GridView1_RowCommand" is present.
In your code behind:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{ /* Set a breakpoint here and make sure:
A.) You are hitting this method
B.) Get value of e.CommandName */
if (e.CommandName == "EditRecord")
{
// Run your edit/update logic here if needed
}
if (e.CommandName == "DeleteRecord")
{
// Delete the record here
string UserId = GridView1.DataKeys[e.RowIndex].Value.ToString();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString());
SqlCommand dCmd = new SqlCommand();
{
conn.Open();
dCmd.CommandText = "Reviewer_Delete";
dCmd.CommandType = CommandType.StoredProcedure;
dCmd.Parameters.Add("#UserId", SqlDbType.NVarChar).Value = UserId;
dCmd.Connection = conn;
dCmd.ExecuteNonQuery();
// Refresh the data
BindDropDownList1();
dCmd.Dispose();
conn.Close();
conn.Dispose();
}
}
This ended up being a very simple thing. On the aspx page I had both the OnRowDeleting and CommandName elements set to the same value of "DeleteRecord".
Changing the CommandName value to "Delete" allowed the code to be evaluated and the stored procedure to be called successfully.

selecting the row in gridview using row index

protected void select_click(object sender, GridViewCommandEventArgs e)
{
try
{
DBLibrary db = new DBLibrary();
int index = Convert.ToInt32(e.CommandArgument);
* string FeeId = gridv1.Rows[index].Cells[1].Text;*
if (e.CommandName == "Select")
{
string str = "SELECT AnuFeeMaster.FeeId ,AnuFeeMaster.StudentId, Tbl_Student.SName, AnuFeeMaster.Month, AnuFeeMaster.Year, AnuFeeMaster.FeeAmount, " +
" AnuFeeMaster.PaidAmount FROM AnuFeeMaster INNER JOIN Tbl_Student ON AnuFeeMaster.StudentId = Tbl_Student.StudentId where ( AnuFeeMaster.FeeId ='" + FeeId + "')";
SqlDataReader dr = db.ExecuteReader(str);
while (dr.Read())
{
Session["name"] = dr["sname"].ToString();
Session["id"] = dr["StudentId"].ToString();
Session["mth"] = dr["Month"].ToString();
Session["yr"] = dr["Year"].ToString();
Session["tot"] = dr["FeeAmount"].ToString();
}
}
}
catch { }
}
Above is my code what i used to access that i am not getting the value r data from dat Please suggest me, * mark which i used that show where i am getting the error
create proper grid rowcommand Event
aspx code
<asp:GridView ID="Gv" runat="server" AllowPaging="true" OnRowCommand="Gv_RowCommand" PageSize="10" EmptyDataText="No Records Found !">
<Columns>
<asp:TemplateField HeaderText="Action" ItemStyle-Width="20%">
<ItemTemplate>
<asp:LinkButton ID="lnkview" runat="server" CommandArgument='<%#Eval("Demo_Code") %>' CommandName="select" ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Coulmn1" HeaderText="Coulmn2" />
<asp:BoundField DataField="Coulmn2" HeaderText="Coulmn2" />
</Columns>
</asp:GridView>
aspx.cs Code
protected void Gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "select")
{
}
}
You should properly use RowCommand event of gridview.
void CustomersGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="Select")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = CustomersGridView.Rows[index];
}
}
You can catch the button click event like below:
protected void MyButtonClick(object sender, System.EventArgs e)
{
//Get the button that raised the event
Button btn = (Button)sender;
//Get the row that contains this button
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
}

Javascript confirmation Box not appear on delete in gridview

When click on delete link-button in gridview, Confirmation Box not appeared. I write this code but I don't know why it's not working...
<asp:GridView ID="gvwAuctionExport" runat="server" AutoGenerateColumns="false" OnRowCommand="gvwAuctionExport_RowCommand" OnRowDataBound="gvwAuctionExport_RowDataBound" OnRowDeleting="gvwAuctionExport_RowDeleting">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<div class="btn-group btn-group-xs" id="bgroup">
<asp:LinkButton ID="lnkInspectionDelete" runat="server" Text="Delete" CssClass="btn btn-danger" CommandArgument='<%# Eval("inspection_id") %>' CommandName="Delete"></asp:LinkButton>
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="address" HeaderText="Address" />
<asp:BoundField DataField="city" HeaderText="City" />
<asp:BoundField DataField="state" HeaderText="State" />
</Columns>
</asp:GridView>
protected void gvwAuctionExport_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int InspectionID = Convert.ToInt32(e.CommandArgument);
string status = string.Empty;
status = DACls.DeleteInspectionByID(InspectionID);
}
}
protected void gvwAuctionExport_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton l = (LinkButton)e.Row.FindControl("lnkInspectionDelete");
l.Attributes.Add("onclick", "javascript:return " +
"confirm('Are you sure you want to delete this record");
}
}
protected void gvwAuctionExport_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
bindGridView();
}
public void bindGridView(){
DataSet DS = new DataSet();
SqlConnection DBCon = new SqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString);
SqlCommand Cmd = new SqlCommand("USP_Inspection_Export", DBCon);
Cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter AHadp = new SqlDataAdapter(Cmd);
AHadp.Fill(this.DS);
DataTable dt = DS.Tables[0];
this.gvwAuctionExport.DataSource = dt;
this.gvwAuctionExport.DataBind();
}
When I click on delete button and check from debugger it is not going to GridView RowDataBound function scope. I don't know what happening here?

Storing BoundField Value in HiddenField on Button Click

I'm having trouble with setting a HiddenField's value to a GridView item value. What I want to do is get the value of a BoundField (in this case, "FIPSCountyCode") in a GridView and store it in a HiddenField when the user clicks a button (in this case, "btnEdit") to make changes to a entry in the grid. I haven't used HiddenFields before, so I have forgotten what to do here.
The HiddenField is setup like this:
<asp:HiddenField ID="hdnFIPS" Value='<%#Eval("FIPSCountyCode")%>' runat="server" />
This is what the GridView is setup like:
<asp:GridView ID="CountyList" runat="server" AutoGenerateColumns="False" Width="90%" SkinId="PagedList" PagerSettings-Position="TopAndBottom" PagerStyle-Wrap="True">
<Columns>
<asp:BoundField HeaderText="County Code" DataField="FIPSCountyCode" />
<asp:BoundField HeaderText="State Code" DataField="StateCode" />
<asp:BoundField HeaderText="County Name" DataField="CountyName" />
<asp:BoundField HeaderText="Tax Rate" DataField="TaxRate" />
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="btnEdit" runat="server" SkinID="EditIcon" OnClick="EditInfo" CommandName="DoEdit" />
<asp:ImageButton ID="DeleteButton" runat="server" SkinID="DeleteIcon" CommandName="DoDelete"
OnClientClick="return confirm('Are you sure you want to remove this item and all of its options?')"
CausesValidation="false" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle CssClass="even" />
</asp:GridView>
And this is the code behind:
public partial class Admin_County_Info : CommerceBuilder.UI.AbleCommerceAdminPage
{
private string redirectString = String.Empty;
protected void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
PopulateCountyGrid();
}
protected void PopulateCountyGrid()
{
try
{
System.Data.SqlClient.SqlDataReader dr = null;
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
SqlCommand cmd = new SqlCommand("SELECT [FIPSCountyCode], [StateCode], [CountyName], [TaxRate] FROM [baird_InfoCounty]", cn);
cmd.CommandType = CommandType.Text;
cn.Open();
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
CountyList.DataSource = dr;
CountyList.DataBind();
}
}
catch (Exception eX)
{
}
}
#region Clicks and Event Handlers
protected void EditInfo(object sender, System.EventArgs e)
{
if (Page.IsValid)
{
redirectString = "~/Admin/Taxes/AddEditCountyInfo.aspx?FIPSCountyCode=" + hdnFIPS.Value;
Response.Redirect(redirectString);
}
}
protected void AddInfo(object sender, System.EventArgs e)
{
if (Page.IsValid)
{
Response.Redirect("~/Admin/Taxes/AddEditCountyInfo.aspx");
}
}
}
This must be a really dumb question but I'm really not sure how to proceed. Any help would be great!
You can get the value of FIPSCountyCode from the BoundField this way:
protected void EditInfo(object sender, System.EventArgs e)
{
if (Page.IsValid)
{
GridViewRow gvr = ((ImageButton)sender).NamingContainer as GridViewRow;
hdnFIPS.Value = gvr.Cells[0].Text;
redirectString = "~/Admin/Taxes/AddEditCountyInfo.aspx?FIPSCountyCode=" + hdnFIPS.Value;
Response.Redirect(redirectString);
}
}

GridView RowUpdating returns old values after PostBack

I got a problem with my GridView. When I try to edit my GridView, I only get the old values in return.
Here's the RowUpdating event:
protected void grid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
TextBox nVorname = (TextBox)row.FindControl("newVorname");
TextBox nNachname = (TextBox)row.FindControl("newNachname");
TextBox nTelnr = (TextBox)row.FindControl("newTelnr");
TextBox nEmail = (TextBox)row.FindControl("newEmail");
HiddenField tid = (HiddenField)row.FindControl("id");
grid.EditIndex = -1;
SqlConnection sqlConn = new SqlConnection("server=localhost;Integrated Security=true;database=Telefonbuch;");
sqlConn.Open();
SqlCommand cmd = new SqlCommand("update dasOertliche set vorname= #vorname, nachname=#nachname, telefonnr =#telnr, email =#email where id = #id", sqlConn);
cmd.Parameters.Add("#vorname", SqlDbType.VarChar);
cmd.Parameters["#vorname"].Value = nVorname;
cmd.Parameters.Add("#nachname", SqlDbType.VarChar);
cmd.Parameters["#nachname"].Value = nNachname.Text;
cmd.Parameters.Add("#email", SqlDbType.VarChar);
cmd.Parameters["#email"].Value = nEmail.Text;
cmd.Parameters.Add("#telnr", SqlDbType.VarChar);
cmd.Parameters["#telnr"].Value = nTelnr.Text;
cmd.Parameters.Add("#id", SqlDbType.Int);
cmd.Parameters["#id"].Value = tid.Value;
cmd.ExecuteNonQuery();
sqlConn.Close();
bind();
}
The TemplateField from the .aspx:
<Columns>
<asp:TemplateField HeaderText = "Vorname">
<ItemTemplate> <%#Eval ("vorname") %></ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="newVorname" runat="server" Text='<%#Eval ("vorname") %>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</columns>
And my GridView code:
<asp:GridView runat="server" ID="grid" BorderWidth="0px" CellPadding="10"
CellSpacing="10" HorizontalAlign="Center" AutoGenerateDeleteButton="True"
AutoGenerateEditButton="True" onrowcancelingedit="grid_RowCancelingEdit"
onrowediting="grid_RowEditing" onrowupdating="grid_RowUpdating"
AutoGenerateColumns="False">
Like I said, it always returns the old values. Any suggestions?
My Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
bind();
if (!Page.IsPostBack)
{
bind();
}
}
My bind():
public void bind()
{
SqlConnection sqlConn = new SqlConnection("server=localhost;Integrated Security=true;database=Telefonbuch;");
sqlConn.Open();
SqlDataAdapter sqlComm = new SqlDataAdapter("SELECT id, vorname AS 'Vorname', nachname AS 'Nachname', telefonnr, email AS 'E-Mail' FROM dasOertliche ORDER BY nachname ASC", sqlConn);
DataSet ds = new DataSet();
sqlComm.Fill(ds, "dasOertliche");
grid.DataSource = ds.Tables[0];
grid.DataBind();
sqlConn.Close();
}
protected void Page_Load(object sender, EventArgs e)
{
bind();
if (!Page.IsPostBack)
{
bind();
}
}
is wrong.
It should be:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
bind();
}
}
On Pageload put your bind grid code in following condition
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
bind();
}
}
You need to call GridView1.DataBind() in the end.

Categories

Resources