I am creating a system in which i want to edit several records from the database through administrator using a data grid view:
Table Schema used in this is
CREATE TABLE [dbo].[tbl_Employee] (
[ID] INT NOT NULL,
[Name] VARCHAR (50) NULL,
[City] VARCHAR (50) NULL,
PRIMARY KEY CLUSTERED ([ID] ASC)
);
I have added Add OnRowEditing, OnRowUpdating and OnRowCancelingEdit events to the GridView.
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="6" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btn_Edit" runat="server" Text="Edit" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="btn_Update" runat="server" Text="Update" CommandName="Update"/>
<asp:Button ID="btn_Cancel" runat="server" Text="Cancel" CommandName="Cancel"/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lbl_ID" runat="server" Text='<%#Eval("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lbl_Name" runat="server" Text='<%#Eval("Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_Name" runat="server" Text='<%#Eval("Name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<ItemTemplate>
<asp:Label ID="lbl_City" runat="server" Text='<%#Eval("City") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_City" runat="server" Text='<%#Eval("City") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#663300" ForeColor="#ffffff"/>
<RowStyle BackColor="#e7ceb6"/>
</asp:GridView>
</div>
And the c# code
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
//Connection String from web.config File
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con;
SqlDataAdapter adapt;
DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
ShowData();
}
}
//ShowData method for Displaying Data in Gridview
protected void ShowData()
{
dt = new DataTable();
con = new SqlConnection(cs);
con.Open();
adapt = new SqlDataAdapter("Select ID,Name,City from tbl_Employee",con);
adapt.Fill(dt);
if(dt.Rows.Count>0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
con.Close();
}
protected void GridView1_RowEditing(object sender, System.Web.UI.WebControls.GridViewEditEventArgs e)
{
//NewEditIndex property used to determine the index of the row being edited.
GridView1.EditIndex = e.NewEditIndex;
ShowData();
}
protected void GridView1_RowUpdating(object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e)
{
//Finding the controls from Gridview for the row which is going to update
Label id=GridView1.Rows[e.RowIndex].FindControl("lbl_ID") as Label;
TextBox name = GridView1.Rows[e.RowIndex].FindControl("txt_Name") as TextBox;
TextBox city = GridView1.Rows[e.RowIndex].FindControl("txt_City") as TextBox;
con = new SqlConnection(cs);
con.Open();
//updating the record
SqlCommand cmd = new SqlCommand("Update tbl_Employee set Name='"+name.Text+"',City='"+city.Text+"' where ID="+Convert.ToInt32(id.Text),con);
cmd.ExecuteNonQuery();
con.Close();
//Setting the EditIndex property to -1 to cancel the Edit mode in Gridview
GridView1.EditIndex = -1;
//Call ShowData method for displaying updated data
ShowData();
}
protected void GridView1_RowCancelingEdit(object sender, System.Web.UI.WebControls.GridViewCancelEditEventArgs e)
{
//Setting the EditIndex property to -1 to cancel the Edit mode in Gridview
GridView1.EditIndex = -1;
ShowData();
}
}
The code is not showing any error but the database is not getting updated.
Where am i going wrong?
Related
I have a gridview like below:
<asp:GridView ID="gvitems" runat="server" AutoGenerateColumns="false" CssClass="GridStyle" AllowSorting="true" OnSorting="OnSorting" DataKeyNames="Id" OnRowCommand="gv_RowCommand"
OnRowEditing="gv_RowEditing" OnRowUpdating="gv_RowUpdating" OnRowCancelingEdit="gv_RowCancelEdit" >
<Columns>
<asp:buttonfield buttontype="Link"
commandname="View"
text="View"/>
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" Text="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button runat="server" Text="Update" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Next Steps">
<ItemTemplate>
<asp:Label runat="server" ID="lblNextSteps" Text='<%# Eval("NextSteps")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtNextSteps" Text='<%# Eval("NextSteps")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox runat="server" ID="txtNextStepsFooter"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And in the backend, this is how i fill it with data:
DataSet dataSet = null;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindGrid_SubmittedProjects();
}
}
private void BindGrid_SubmittedProjects(string sortExpression = null)
{
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ProjectsDataBase"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("ViewProjects", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#UserName", SqlDbType.VarChar).Value = "myusername";
cmd.Connection = con;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
dataSet = new DataSet();
sda.Fill(dataSet, "Project");
}
gvitems.DataSource = dataSet.Tables[0].DefaultView;
gvitems.DataBind();
}
}
}
When I click on the "View" hyperlink on each row, it works, so OnRowCommand function below is triggered.
protected void gv_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "View")
{
//my work
}
}
However, when I click on "Edit" button, nothing is happening, OnRowEditing is not being triggered.
protected void gv_RowEditing(Object sender, GridViewEditEventArgs e)
{
gvitems.EditIndex = e.NewEditIndex;
this.BindGrid_SubmittedProjects();
}
protected void gv_RowUpdating(Object sender, GridViewUpdateEventArgs e)
{
//my update query.
}
I could not see what I am doing wrong. Tried many things I've found over online but none worked. Any help would be so appreciated.
Regards.
Using LinkButton instead of regular button fixed the issue.
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton Text="Edit" runat="server" CommandName="Edit" />
<asp:LinkButton Text="Delete" runat="server" CommandName="Delete" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton Text="Update" runat="server" CommandName="Update" />
<asp:LinkButton Text="Cancel" runat="server" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
I am trying to update the record by using gridview by using n tier applications. My insert and delete is working but when I tried to update the record from gridview update button it not updating the record and retrieving old record.
Here is the store procedure
CREATE PROCEDURE [dbo].[UpdateJob]
(
#Job_ID int ,
#Title [varchar](50) ,
#Location [varchar](50),
#Exprience [varchar](500),
#Type_Contract [varchar](50) ,
#Posted_Date [varchar](50),
#Salary [varchar](50)
)
AS
update Job_Profile
set
#Title = #Title,
#Location = #Location,
#Exprience = #Exprience,
#Type_Contract = #Type_Contract,
#Posted_Date = #Posted_Date,
#Salary = #Salary
where
#Job_ID = #Job_ID
RETURN
GO
Here is my methods .
public void Job_update(int Job_ID, string title, string location, string exprience, string type_Contract, string posted_Date, string salary)
{
SqlConnection con = new SqlConnection(#"Data Source=NIRJOR\SQLEXPRESS;Initial Catalog=StudentJobPortal;Integrated Security=True");
SqlCommand cmd = new SqlCommand("UpdateJob", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("Job_Id", Job_ID);
cmd.Parameters.AddWithValue("Title", title);
cmd.Parameters.AddWithValue("Location", location);
cmd.Parameters.AddWithValue("Exprience", exprience);
cmd.Parameters.AddWithValue("Type_Contract", type_Contract);
cmd.Parameters.AddWithValue("Posted_Date", posted_Date);
cmd.Parameters.AddWithValue("Salary", salary);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
}
Here is the html .
<%# Page Title="" Language="C#" MasterPageFile="~/Master.Master" AutoEventWireup="true" CodeBehind="Joblist.aspx.cs" Inherits="StudentJobSite.Pages.Joblist" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
BackColor="LightGoldenrodYellow" BorderColor="Tan" BorderWidth="1px"
CellPadding="2" DataKeyNames="Job_ID" ForeColor="Black" GridLines="None"
AutoGenerateDeleteButton="True" AutoGenerateEditButton="True"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"
onrowupdating="GridView1_RowUpdating">
<AlternatingRowStyle BackColor="PaleGoldenrod" />
<Columns>
<asp:TemplateField HeaderText="Job ID">
<EditItemTemplate>
<asp:Label ID="lbljobID" runat="server" Text='<%# Eval("Job_ID")%>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Job_ID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Title">
<EditItemTemplate>
<asp:TextBox ID="txtTitle" runat="server" Text='<%# Bind("Title")%>' Width="100px"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Title")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<EditItemTemplate>
<asp:TextBox ID="txtLocation" runat="server" Text='<%# Bind("Location")%>' Width="100px"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("Location")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Exprience">
<EditItemTemplate>
<asp:TextBox ID="txtExprience" runat="server" Text='<%# Bind("Exprience")%>' Width="100px"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("Exprience")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Type Contract">
<EditItemTemplate>
<asp:TextBox ID="txtType_Contract" runat="server" Text='<%# Bind("Type_Contract")%>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("Type_Contract")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Posted Date">
<EditItemTemplate>
<asp:TextBox ID="txtPosted_Date" runat="server" Text='<%# Bind("Posted_Date")%>' Width="100px"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label6" runat="server" Text='<%# Bind("Posted_Date")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Salary">
<EditItemTemplate>
<asp:TextBox ID="txtSalary" runat="server" Text='<%# Bind("Salary")%>' Width="100px"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label7" runat="server" Text='<%# Bind("Salary")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Label ID="lblResult" runat="server" Text=""></asp:Label>
</div>
</asp:Content>
Here is the code behind.
using BusinessLogicLayer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace StudentJobSite.Pages
{
public partial class Joblist : System.Web.UI.Page
{
JobHandler jobHandler = new JobHandler();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
refreshdata();
}
}
public void refreshdata()
{
GridView1.DataSource = jobHandler.GetJobList();
GridView1.DataBind();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int Job_ID = Convert.ToInt16(GridView1.DataKeys[e.RowIndex].Values["Job_ID"].ToString());
jobHandler.job_delete(Job_ID);
refreshdata();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
refreshdata();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Label lblID = GridView1.Rows[e.RowIndex].FindControl("Job_ID") as Label;
TextBox txtTitle = GridView1.Rows[e.RowIndex].FindControl("txtTitle") as TextBox;
TextBox txtLocation = GridView1.Rows[e.RowIndex].FindControl("txtLocation") as TextBox;
TextBox txtExprience = GridView1.Rows[e.RowIndex].FindControl("txtExprience") as TextBox;
TextBox txtType_Contract = GridView1.Rows[e.RowIndex].FindControl("txtType_Contract") as TextBox;
TextBox txtPosted_Date = GridView1.Rows[e.RowIndex].FindControl("txtPosted_Date") as TextBox;
TextBox txtSalary = GridView1.Rows[e.RowIndex].FindControl("txtSalary") as TextBox;
int Job_ID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["Job_ID"].ToString());
jobHandler.job_update(Job_ID, txtTitle.Text, txtLocation.Text, txtExprience.Text, txtType_Contract.Text, txtPosted_Date.Text, txtSalary.Text);
GridView1.EditIndex = -1;
refreshdata();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
refreshdata();
}
}
}
I'd say the problem is in your stored procedure:
update Job_Profile
set
#Title = #Title,
#Location = #Location,
#Exprience = #Exprience,
#Type_Contract = #Type_Contract,
#Posted_Date = #Posted_Date,
#Salary = #Salary
where
#Job_ID = #Job_ID
RETURN
All this query does, if it's even syntactically valid, is update the input parameters to the same value they already are
An update command that updates a table column(s) with values from parameters would look like:
update Job_Profile
set
Title = #Title,
Location = #Location,
Exprience = #Exprience,
Type_Contract = #Type_Contract,
Posted_Date = #Posted_Date,
Salary = #Salary
where
Job_ID = #Job_ID
RETURN
The things on the left hand side of the = need to be column names. If they start with an # then they aren't column names. # is used at the start of variable names
UPDATE tablename
SET columnName = #variableName
WHERE ...
When you face a problem like this break it down into steps - call this stored procedure with SSMS. It either works or it doesn't. If it works then the problem is in C# code. If it doesn't the n the problem is in SP code.. this is a basic debugging; narrow down the cause of the problem so you're sure where it is occurring
I have a Editable GridView that I'm attempting to add sorting functionalty to specified columns. Though I receive no errors, My sorting method does not work. Could I please get some help on what I'm missing here?
The Design:
<asp:GridView ID="gvLogNotice"
runat="server"
AutoGenerateColumns="false"
ShowFooter="false"
OnRowCancelingEdit="gvLogNotice_RowCancelingEdit"
OnRowEditing="gvLogNotice_RowEditing"
OnRowUpdating="gvLogNotice_RowUpdating"
EmptyDataText="There are no data records to display."
DataKeyNames="LogNoticeID"
AllowPaging="true"
AllowSorting="true"
OnSorting="gvLogNotice_sorting"
Width="700px">
<Columns>
<asp:TemplateField HeaderText="Log No." Visible="false">
<ItemTemplate>
<%#Eval("LogNoticeID")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLogNoticeID" runat="server" Enabled="false" Text=' <%#Eval("LogNoticeID") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Log Date" SortExpression="DateLogged">
<ItemTemplate>
<%#Eval("DateLogged")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDateLogged" runat="server" Text=' <%#Eval("DateLogged") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Log Description" HeaderStyle-Width="50px" sortexpression="LogNoticeDescript">
<ItemTemplate>
<%#Eval("LogNoticeDescript")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLogNoticeDescript" runat="server" Text=' <%#Eval("LogNoticeDescript") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Responsible Party" sortexpression="ResponsibleParty">
<ItemTemplate>
<%#Eval("ResponsibleParty")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtResponsibleParty" runat="server" Text=' <%#Eval("ResponsibleParty") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Planned Date" SortExpression="PlannedDate" >
<ItemTemplate>
<%#Eval("PlannedDate")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtPlannedDate" runat="server" Text=' <%#Eval("PlannedDate") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Case Number" SortExpression="CaseNumber">
<ItemTemplate>
<%#Eval("CaseNumber")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCaseNumber" runat="server" Text=' <%#Eval("CaseNumber") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Log Status" SortExpression="LogStatus">
<ItemTemplate>
<%#Eval("LogStatus")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLogStatus" runat="server" Text=' <%#Eval("LogStatus") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="images/edit.png" Width="25"
Height="25" CommandName="Edit" />
<%-- <asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="~/img/delete.png" CommandName="Delete"
OnClientClick="return confirm('Are you sure want to delete record?')" />--%>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Update">Update</asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind:
//Page Load Event:
protected void Page_Load(object sender, EventArgs e)
{
lblmsg.Text = "";
if (!Page.IsPostBack)
{
gvLogNotice.ShowFooter = false;
//Load grid data using common method
LoadGrid();
}
}
//bind data to GV and Load
void LoadGrid()
{
sqlcmd = new SqlCommand("selectActiveLogs", sqlcon);
sqlcmd.CommandType = CommandType.StoredProcedure;
try
{
sqlcon.Open();
da = new SqlDataAdapter(sqlcmd);
dt.Clear();
da.Fill(dt);
gvLogNotice.DataSource = dt;
gvLogNotice.DataBind();
}
catch (Exception ex)
{
}
finally
{
sqlcon.Close();
}
}
//sorting event
protected void gvLogNotice_sorting(object sender, GridViewSortEventArgs e)
{
switch (e.SortExpression)
{
case "DateLogged":
if (e.SortDirection == SortDirection.Ascending)
{
LoadGrid();
}
else
{
LoadGrid();
}
break;
}
}
The SortDirection property on the GridView is changed only when the GridView is bound to a DataSource control using the DataSourceID property. Otherwise, sort direction needs to be managed manually.
In this case when we provide Data to gridView using its DataSource property , e.SortDirection will always return Ascending. And therefore only your IF statement will always get executed.
Second Point:: You need to optimize actually is just make sure you define a function to return the Data only. e.g say LoadGrid() only returns the DataTable. This way you don't need to define overloads of your LoadGrid() method. Morover, with a proper way of implementation, overloading is really not needed at all.
Third point:: is that you aren't applying sorting at all, but just loading the GridView.When you databind manually by setting the DataSource property and calling DataBind(), you need to handle the sort operation manually.
So, start by storing your sortDirection in ViewState. Simply define a public property to Get/Set the same. [ NOTE we need to store the sortDirection value according to point 1 above ]
public SortDirection SortDirection
{
get {
if (ViewState["SortDirection"] == null)
{
ViewState["SortDirection"] = SortDirection.Ascending;
}
return (SortDirection)ViewState["SortDirection"];
}
set
{
ViewState["SortDirection"] = value;
}
}
In your OnSorting event, Set the sortDirection as well as firstly sort the table and then load it into gridView.
protected void SortRecords(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
string direction = string.Empty;
if (SortDirection == SortDirection.Ascending)
{
SortDirection = SortDirection.Descending;
direction = " DESC";
}
else
{
SortDirection = SortDirection.Ascending;
direction = " ASC";
}
DataTable table = this.LoadGrid(); // or this.GetDataTable(), to get only the DataTable
// Now apply Sorting to your source of Data
table.DefaultView.Sort = sortExpression + direction;
// Bind the GridView
gvLogNotice.DataSource = table;
gvLogNotice.DataBind();
}
And last, your LoadGrid is fine, only thing that just fill the table and return it
private DataTable LoadGrid()
{
DataTable dt = new DataTable();
sqlcmd = new SqlCommand("selectActiveLogs", sqlcon);
sqlcmd.CommandType = CommandType.StoredProcedure;
try
{
sqlcon.Open();
da = new SqlDataAdapter(sqlcmd);
dt.Clear();
da.Fill(dt);
return dt;
}
catch (Exception ex)
{}
}
So I'm using ADO.net Entity Data model in an ASP.Net (C#) Web page. I am dynamically adding and retrieving data to my database using gridviews. I am using master pages, and my gridview is in a contentplaceholder. My only issue with this code is that when my RowUpdating event fires, the gridview is null. I can call by BindGV function, and then the rest of the code updates the database perfectly fine, with the original data from the database I just bound to it, since the database was not updated yet. In all events, if I change bindGV() to Gridview1.databind(), the gridview is null. I think the datasource the gridview is referencing is becoming null at the end of the event when the data connection is closed, is there anyway to prevent this?
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating"
onrowdatabound="GridView1_RowDataBound"
>
<Columns>
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:Label ID="lblId" runat="server" Text='<%# Eval("id") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblId" runat="server" Text='<%# Eval("id") %>'></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Machine">
<ItemTemplate>
<asp:Label ID="lblMachine" runat="server" Text='<%# Eval("MachineName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtMachine" runat="server" Text='<%# Eval("MachineName") %>'></asp:TextBox>
</EditItemTemplate>
<ControlStyle Width="60px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Dept">
<ItemTemplate>
<asp:Label ID="lblDept" runat="server" Text='<%# Eval("WorkCenterFK") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddldept" runat="server" >
</asp:DropDownList>
</EditItemTemplate>
<ControlStyle Width="120px" />
</asp:TemplateField>
<asp:CommandField HeaderText="Actions" ShowEditButton="true" ShowDeleteButton="True"
ControlStyle-Width="50px" CausesValidation="false">
</asp:CommandField>
</Columns>
protected void BindGV()
{
QualityEntities database = new QualityEntities();
GridView1.DataSource = (from m in database.Machines
from d in database.Workcenters
where m.WorkcenterFK == d.id
select
new { id = m.id, MachineName = m.MachineName, WorkCenterFK = d.WorkCenterName }); ;
GridView1.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) BindGV();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGV();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGV();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
QualityEntities database = new QualityEntities();
BindGV();
Int32 id = Convert.ToInt32(((Label)GridView1.Rows[e.RowIndex].FindControl("lblId")).Text);
DropDownList ddl = ((DropDownList)GridView1.Rows[e.RowIndex].FindControl("ddlDept"));
TextBox txt = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtMachine"));
Machine mch = (from m in database.Machines where m.id == id select m).Single();
mch.MachineName = txt.Text;
mch.WorkcenterFK = Convert.ToInt32(ddl.SelectedItem.Value);
database.SaveChanges();
GridView1.EditIndex = -1;
BindGV();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
QualityEntities database = new QualityEntities();
DropDownList temp = (DropDownList)(e.Row.FindControl("ddlDept"));
if (temp != null)
{
temp.DataSource = (from w in database.Workcenters select w);
temp.DataTextField = "WorkCenterName";
temp.DataValueField = "id";
temp.DataBind();
Int32 id = Convert.ToInt32(((Label)e.Row.FindControl("lblId")).Text);
}
}
Not sure why the GridView is null, but instead of using a member variable i would use the sender of the event which is always the source of the event (in this case the GridView)
// ...
GridView grid = (GridView)sender;
Int32 id = Convert.ToInt32(((Label)grid.Rows[e.RowIndex].FindControl("lblId")).Text);
// ...
i am binding the values to gridview like this
<asp:GridView ID="grdViewAttachment_Client" runat="server" Width="615px" AutoGenerateColumns="False" GridLines="None" CssClass="grid-view" OnRowCommand="grdViewAttachment_Client_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Attachment" HeaderStyle-CssClass="hedding2">
<ItemTemplate>
<asp:LinkButton ID="lnkbtnAttachments" runat="server" Text="Delete" CommandName="Delete" CommandArgument='<%#Eval("AttachmentId") %>' ></asp:LinkButton>
</ItemTemplate>
<HeaderStyle/>
</asp:TemplateField>
<asp:TemplateField HeaderText="Attachment" HeaderStyle-CssClass="hedding2">
<ItemTemplate>
<%--<asp:LinkButton ID="lnkbtnAttachments" runat="server" Text='<%#Eval("AttachmentName") %>' CommandName='<%#Eval("AttachmentName")%>' CommandArgument='<%#Eval("AttachmentId") %>'></asp:LinkButton>--%>
<asp:LinkButton ID="LinkButton1" runat="server" Text='<%#Eval("AttachmentName") %>' CommandName='<%#Eval("AttachmentName")%>' ></asp:LinkButton>
</ItemTemplate>
<HeaderStyle/>
</asp:TemplateField>
<asp:TemplateField HeaderText="AssignedTo" HeaderStyle-CssClass="hedding2">
<ItemTemplate>
<asp:Label ID="lblAssignedTo" Text='<%#Eval("AssignedTo") %>' runat="server" CssClass="body-text"></asp:Label>
</ItemTemplate>
<HeaderStyle />
</asp:TemplateField>
<asp:TemplateField HeaderText="CreationDate" HeaderStyle-CssClass="hedding2">
<ItemTemplate>
<asp:Label ID="lblCreationDate" Text='<%#Eval("CreationDate") %>' runat="server" CssClass="body-text"></asp:Label>
</ItemTemplate>
<HeaderStyle />
</asp:TemplateField>
</Columns>
</asp:GridView>
In my row command event i write as follows code
protected void grdViewAttachment_Client_RowCommand(object sender, GridViewCommandEventArgs e)
{
SqlConnection m_Conn = new SqlConnection(Utilities.ConnectionString());
SqlCommand m_oCmd;
int iStID = int.Parse(e.CommandArgument.ToString());
int pk = 0;
int.TryParse(e.CommandArgument as string, out pk);
string strStoreProcName = null;
DataSet oDS1 = new DataSet();
if (e.CommandName == "Delete")
{
strStoreProcName = StoredProcNames.Attachments_uspDeleteAttachs;
m_oCmd = new SqlCommand(strStoreProcName, m_Conn);
m_oCmd.CommandType = CommandType.StoredProcedure;
m_oCmd.Parameters.Add("#AttachmentId", SqlDbType.Int).Value = Convert.ToInt32(e.CommandArgument.ToString());
m_Conn.Open();
m_oCmd.ExecuteNonQuery();
AttachmentDetails();
}
string fname = e.CommandName.ToString();
}
But i am not getting the value i am getting the exception as Input string was not in correct format can any one help me
es #Muhammad Akhtar was right .It should be like
int iStID = Convert.ToInt32(gridName.DataKeys[Convert.ToInt32(e.CommandArgument.ToString())].Value);
Specify Datakey property in your data grid . and you can access the data key value of the current row as above
add datakey name to your statement
ID_COLUMN should be a column from data table which you are binding to gridview
Write this code for row Created
protected void grdViewAttachment_Client_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lnkbtnAttachments=(LinkButton)e.Row.FindControl("lnkbtnAttachments");
lnkbtnAttachments.CommandArgument = e.Row.RowIndex.ToString();
// similarly write for other controls
}
}
Do not use Delete standard commandName otherwise you have to handle the "RowDeleting" event.
Take a look at this sample:
.aspx markup
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
onrowcommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
Data :
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
<asp:LinkButton ID="btnDelete" runat="server"
CommandArgument='<%# Eval("No") %>' CommandName="Del">Delete</asp:LinkButton>
<asp:LinkButton ID="btnShow" runat="server" CommandArgument='<%# Eval("No") %>'
CommandName="Show">Show</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind
public class Data
{
public int No { get; set; }
public string Name { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<Data> list = new List<Data>()
{
new Data(){ No=1, Name="A"},
new Data(){ No=2, Name="B"},
new Data(){ No=3, Name="C"}
};
GridView1.DataSource = list;
GridView1.DataBind();
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Del")
{
Response.Write("Delete : " + e.CommandArgument);
}
else
if (e.CommandName == "Show")
{
Response.Write("Show : " + e.CommandArgument);
}
}
As you are not passing command Argument this will always give null reference . Try this in your control where ever you required.
<asp:LinkButton ID="LinkButton1" runat="server" Text='<%#Eval("AttachmentName") %>' CommandName='<%#Eval("AttachmentName")%>' CommandArgument='<%#Eval("AttachmentId") %>'>
<ItemTemplate>
<asp:LinkButton ID="lnkDetails" runat="server" CommandName="Details" CommandArgument='<%#Eval("ID")%>'
ToolTip="View Details">View</asp:LinkButton>
</ItemTemplate>
protected void gvmain_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Details")
{
int id = Convert.ToInt32(e.CommandArgument);
Response.Redirect("~/MEMBER/UploadedDocList.aspx?id=" + id, false);
}
}