Updating Cells in Gridview

I am trying to update any field in the gridview that needs updating when the user clicks on the Update link on the page.  I have attached my code below.  Everything else is working fine.  It is just the updating step is a little tough. How would I pass the field to update the stored procedure for the row that I am editing?
 I don't know where to start in the updating event.  Please provide assistance as it will be greatly appreciated.
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
 
public partial class Report_TagTime_Maintenance : System.Web.UI.Page
{
 
    DataSet objDS;
 
    protected void Page_Load(object sender, EventArgs e)
    {
 
 
        string strQuery = "SELECT * FROM NCSecurityRolesDescriptions";
        objDS = getDataSet(ConfigurationManager.ConnectionStrings["CNTSTR"].ToString(), strQuery);
        GridView1.DataSource = objDS;
        GridView1.DataBind();
 
    }
 
 
    public DataSet getDataSet(string connectString, string queryString)
    {
        SqlConnection objConn = null;
        SqlCommand objComm = null;
        SqlDataAdapter objDA = null;
        DataSet objTempDS = null;
 
        try
        {
            objConn = new SqlConnection(connectString);
            objComm = new SqlCommand(queryString, objConn);
            objDA = new SqlDataAdapter(objComm);
            objTempDS = new DataSet();
            objDA.Fill(objTempDS);
        }
        catch (Exception ex)
        {
            //write to a log file all errors
            string error = ex.Message;
        }
        #region explicit disposal of objects
        finally
        {
            if (objConn.State.Equals(ConnectionState.Open))
            {
                objConn.Close();
            }
            if (objConn != null)
            {
                objConn.Dispose();
            }
            if (objComm != null)
            {
                objComm.Dispose();
            }
            if (objDA != null)
            {
                objDA.Dispose();
            }
        }
        #endregion
 
        return objTempDS;
    }
 
 
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
 
        GridView1.EditIndex = e.NewEditIndex;
 
        BindData();
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
 
        BindData();
        
 
    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
 
        BindData();
    }
 
    void BindData()
    {
        string strQuery = "SELECT * FROM NCSecurityRolesDescriptions";
        objDS = getDataSet(ConfigurationManager.ConnectionStrings["CNTSTR"].ToString(), strQuery);
        GridView1.DataSource = objDS;
        GridView1.DataBind();
    }
 
 
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
 
    }
}
 
 
 
 
 
 
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Report_TagTime_Maintenance.aspx.cs" Inherits="Report_TagTime_Maintenance" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <asp:Panel ID="Panel1" runat="server" Height="391px">
             <asp:GridView ID="GridView1" runat="server" Height="400px" 
            AutoGenerateColumns="False" AllowPaging="true" BackColor="White" BorderColor="#999999" 
            BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Vertical" 
                 AutoGenerateEditButton="True" 
                 onpageindexchanging="GridView1_PageIndexChanging" 
                 onrowcancelingedit="GridView1_RowCancelingEdit" 
                 onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating">
            <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
            <RowStyle BackColor="#EEEEEE" ForeColor="Black" />
            <Columns>
                <asp:BoundField DataField="RoutingName" FooterText="RoutingName" 
                    HeaderText="Routing Name" />
                <asp:BoundField DataField="ShortName" FooterText="ShortName" 
                    HeaderText="ShortName" />
                <asp:BoundField DataField="Type" FooterText="Type" HeaderText="Type" />
                <asp:BoundField DataField="Department" FooterText="Department" 
                    HeaderText="Department" />
                </Columns>
            <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
            <AlternatingRowStyle BackColor="#DCDCDC" />
        </asp:GridView>
        </asp:Panel>
    
    </div>
    </form>
</body>
</html>

Open in new window

jedwards_2Asked:
Who is Participating?
 
prairiedogConnect With a Mentor Commented:
OK, it should be similiar to VS 2005. BTW, it seems that you are using the built-in Edit button, so you don't need RowCreated event handler. Sorry.
1. Select the GridView, then at the right upper corner of the GridView you will see a black arrow, click the arrow and select Edit Columns. Then select each column and click "Convert this field into a TemplateField".
2. Go to Edit Template, and select each template that is converted, and assign meaningful names for the control in ItemTemplate and EditTemplate (i.e. txtRountingName, txtShortName, etc).
4. I attached the RowUpdating event handler to help you move on because I get off work at 5 and it will be hard for me to follow up with you once I am home.

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
	int id = int.Parse(this.GridView1.DataKeys[e.RowIndex].Value.ToString());
	GridViewRow gvr = this.GridView1.Rows[e.RowIndex];
	TextBox txtRountingName = (TextBox)gvr.FindControl("txtRoutingName");
	TextBox txtShortName = (TextBox)gvr.FindControl("txtShortName");
	TextBox txtType = (TextBox)gvr.FindControl("txtType");
	TextBox txtDepartment = (TextBox)gvr.FindControl("txtDepartment");
	// now you can pass txtRoutingName.Text, txtShortName.Text
	// txtType.Text, txtDepartment, and id to your stored procedure
	// for updating.
}

Open in new window

0
 
prairiedogCommented:
1. Move DataSet objDS; into BindData method
2. Change Page_Load event handler as the attached code snippet shows.
3. Which fields of the four BoundFields are editable?

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
       BindData();
    }  
}

Open in new window

0
 
jedwards_2Author Commented:
OK.  The fields below are bound fields.  I want to update these in a stored procedure.
<Columns>
                <asp:BoundField DataField="RoutingName" FooterText="RoutingName" 
                    HeaderText="Routing Name" />
                <asp:BoundField DataField="ShortName" FooterText="ShortName" 
                    HeaderText="ShortName" />
                <asp:BoundField DataField="Type" FooterText="Type" HeaderText="Type" />
                <asp:BoundField DataField="Department" FooterText="Department" 
                    HeaderText="Department" />
                </Columns>

Open in new window

0
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
prairiedogCommented:
Hi jedwards_2,
Just found out this is a duplicate question that you posted. I understand you need your question to be answered quickly, but posting duplicate question will cause confusion. You need to decide which one to keep and close/delete the other one, then we can continue on.
0
 
jedwards_2Author Commented:
I requested to delete the other question already.  You right.  I am at the end of this project.
0
 
prairiedogCommented:
OK. I need you to follow the following steps:
1. Add DataKeyNames = "YourPrimaryKeyField" to your GridView, because we will need it to update the record ( I assume you need this in your store procedure, if not, let me know.)
2. Add a RowCreated event handler to your GridView.
3. To make life easier, convert those four BoundFields into TemplateFields. Then give meaningful ID's for those four TextBox controls (after conversion, go to Edit Template, you will see those TextBox controls in EditTemplate)
Let me know when you finish the above steps and we can go from there.
0
 
jedwards_2Author Commented:
Added DataKeyName in the ASPX file.

Added a RowUpdated Event Handler

Need some help with conversion.  Don't know where to start
0
 
prairiedogCommented:
1. RowCreated, not RowUpdated.
2. Do you use VS 2005?
 
0
 
jedwards_2Author Commented:
Using VS 2008   using 2.0 framework
0
 
prairiedogCommented:
Hi jedwards_2,
How is it going now?
0
 
jedwards_2Author Commented:
Got it to work.  Thank you....

Quick questions how could I take one of those fields and change it to a dropdown then Bind the dropdown through C Sharp code.  my final code is below.
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
 
public partial class Report_TagTime_Maintenance : System.Web.UI.Page
{
 
    DataSet objDS;
 
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindData();
        }  
 
 
     }
 
 
    protected void BindData()
    {
        string strQuery = "SELECT * FROM NCSecurityRolesDescriptions";
        objDS = getDataSet(ConfigurationManager.AppSettings["NCConnString"].ToString(), strQuery);
        GridView1.DataSource = objDS;
        GridView1.DataBind(); 
 }
 
    public DataSet getDataSet(string connectString, string queryString)
    {
        SqlConnection objConn = null;
        SqlCommand objComm = null;
        SqlDataAdapter objDA = null;
        DataSet objTempDS = null;
 
        try
        {
            objConn = new SqlConnection(connectString);
            objComm = new SqlCommand(queryString, objConn);
            objDA = new SqlDataAdapter(objComm);
            objTempDS = new DataSet();
            objDA.Fill(objTempDS);
        }
        catch (Exception ex)
        {
            //write to a log file all errors
            string error = ex.Message;
        }
        #region explicit disposal of objects
        finally
        {
            if (objConn.State.Equals(ConnectionState.Open))
            {
                objConn.Close();
            }
            if (objConn != null)
            {
                objConn.Dispose();
            }
            if (objComm != null)
            {
                objComm.Dispose();
            }
            if (objDA != null)
            {
                objDA.Dispose();
            }
        }
        #endregion
 
        return objTempDS;
    }
 
 
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
 
        GridView1.EditIndex = e.NewEditIndex;
 
        BindData();
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
 
        BindData();
        
 
    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
 
        BindData();
    }
 
 
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        int id = int.Parse(this.GridView1.DataKeys[e.RowIndex].Value.ToString());
        GridViewRow gvr = this.GridView1.Rows[e.RowIndex];
        TextBox txtRoutingName = (TextBox)gvr.FindControl("txtRoutingName");
        TextBox txtShortName = (TextBox)gvr.FindControl("txtShortName");
        TextBox txtType = (TextBox)gvr.FindControl("txtType");
        TextBox txtDepartment = (TextBox)gvr.FindControl("txtDepartment");
 
 
        SqlConnection objconn = new SqlConnection(ConfigurationManager.AppSettings["NCConnString"].ToString());
 
        SqlCommand mCommand = new SqlCommand("UpdateNCMaintenance", objconn);
        mCommand.CommandType = CommandType.StoredProcedure;
        mCommand.Parameters.Add(new SqlParameter("@vRoutingName", SqlDbType.VarChar, 75));
        mCommand.Parameters["@vRoutingName"].Value = txtRoutingName.Text.ToString();
        mCommand.Parameters.Add(new SqlParameter("@vShortName", SqlDbType.VarChar, 75));
        mCommand.Parameters["@vShortName"].Value = txtShortName.Text.ToString();
        mCommand.Parameters.Add(new SqlParameter("@vType", SqlDbType.VarChar, 75));
        mCommand.Parameters["@vType"].Value = txtType.Text.ToString();
        mCommand.Parameters.Add(new SqlParameter("@vDepartment", SqlDbType.VarChar, 75));
        mCommand.Parameters["@vDepartment"].Value = txtDepartment.Text.ToString();
        mCommand.Parameters.Add(new SqlParameter("@vID", SqlDbType.VarChar, 75));
        mCommand.Parameters["@vID"].Value = id;
        objconn.Open();
        mCommand.ExecuteNonQuery();
        objconn.Close();
        GridView1.EditIndex = -1;
        BindData(); 
 
 
    }
 
}
 
 
 
 
 
 
 
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Report_TagTime_Maintenance.aspx.cs" Inherits="Report_TagTime_Maintenance" %>
 
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
    <style type="text/css">
        .style1
        {
            width: 100%;
        }
        .style2
        {
        	width: 200px
        }
        .style3
        {
        	font-style:normal;
            color:Blue;
            font-weight:bolder;
            font-size:x-large;
        }
            
    </style>
</asp:Content>
       <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
        <asp:Panel ID="Panel1" runat="server" Height="391px">
             <asp:GridView ID="GridView1" runat="server" Height="400px" 
            AutoGenerateColumns="False" AllowPaging="True" BackColor="White" BorderColor="#999999" 
            BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Vertical" 
                 AutoGenerateEditButton="True" DataKeyNames="ID" 
                 onpageindexchanging="GridView1_PageIndexChanging" 
                 onrowcancelingedit="GridView1_RowCancelingEdit" 
                 onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating" 
                 Width="744px">
            <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
            <RowStyle BackColor="#EEEEEE" ForeColor="Black" />
            <Columns>
                <asp:TemplateField FooterText="RoutingName" HeaderText="Routing">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtRoutingName" runat="server" Text='<%# Bind("RoutingName") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("RoutingName") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField FooterText="ShortName" HeaderText="ShortName">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtShortName" runat="server" Text='<%# Bind("ShortName") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label2" runat="server" Text='<%# Bind("ShortName") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField FooterText="Type" HeaderText="Type">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtType" runat="server" Text='<%# Bind("Type") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label3" runat="server" Text='<%# Bind("Type") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField FooterText="Department" HeaderText="Department">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtDepartment" runat="server" Text='<%# Bind("Department") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label4" runat="server" Text='<%# Bind("Department") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                </Columns>
            <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
            <AlternatingRowStyle BackColor="#DCDCDC" />
     </asp:GridView>
     </asp:Panel>
</asp:Content>

Open in new window

0
 
prairiedogCommented:
With all respect, it should be a new question because it involves more coding, not just copy and replace a field. But I can give you some basic ideas on how to do it.
If the DropDownList is not bound to database, then just add a DropDownList control in EditTemplate, add items to the dropdownlist, then set SelectedValue='<%#Bind("FieldName")%>', and you are done.
But if the DropDownList is bound to a database, then it will involve more coding. Still add a DDL in EditTemplate, set SelectedValue='<%Bind("FieldName")%>'. Then you will need to use RowDataBound event handler to find the editing row, load data for the DDL, then bind the DDL to the data.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.