Ruan
Ruan

Reputation: 4293

ASP.Net How to Update a database from a gridview C#

How would you update a SQL database from a gridview? (after a record has been updated)

Using - SharePoint -> Application page - I know, SharePoint...."Making the basic things more basic and the hard things Impossible" (There's not even a SQLDatasource control on the side, you have to add it yourself if you want it - don't know if they don't want you to add one to the project or something...)

I have data being displayed in the gridview, and enabled the

  AutoGenerateEditButton="True" 

in the gridview. And the gridview's datasource is a dataset I populated from my database.

I Take it that without a SQLDatasource thats bound to your gridview, you will have to connect to the database again and update the database manually. But I cant seem to find any way to do this other than the SQLDataSource that is bound to the gridview that does the updating automatically.

Ways to do this but Requires the SQLDatasource bound to the gridview

Method Nr1

Method Nr2

How will you go about updating the database after editing the gridview?

--Update Solution-- Added a few modifications. Thanks

  protected void Page_Load(object sender, EventArgs e)
        {
            int employeerId = 1;
            //Add all the employees to the list to view them.
            string query = "select emp.Name as [Employee Name], em.* from EthicsManagement em join EmployeeTable emp on em.employeeId = emp.employeeId where emp.managerId =" + employeerId;

            DataSet ds = dbConn.returnSqlDataset(query);
            grdViewDetails.DataSource = ds;
            grdViewDetails.DataBind();
            int x  = grdViewDetails.Columns.Count;

            //Hide the columns.
            grdViewDetails.DataBind();
            if (grdViewDetails.Columns.Count > 0)
            {
                grdViewDetails.Columns[2].Visible = false;
                grdViewDetails.Columns[3].Visible = false;
            }
            else
            {
                grdViewDetails.HeaderRow.Cells[0].Visible = false;
                foreach (GridViewRow gvr in grdViewDetails.Rows)
                {
                    gvr.Cells[2].Visible = false;
                    gvr.Cells[3].Visible = false;
                }
            }
        }


protected void grdViewDetails_RowEditing1(object sender, GridViewEditEventArgs e)
    {
        string query = "select emp.Name as [Employee Name], em.* from EthicsManagement em join EmployeeTable emp on em.employeeId = emp.employeeId where emp.managerId =" + 1;
        grdViewDetails.EditIndex = e.NewEditIndex;
        //e.newedit index:- will be provide index of row for which edit button is selected
        grdViewDetails.DataSource = dbConn.returnSqlDataset(query);
        grdViewDetails.DataBind();
    }



    protected void grdViewDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        string query = "select emp.Name as [Employee Name], em.* from EthicsManagement em join EmployeeTable emp on em.employeeId = emp.employeeId where emp.managerId =" + 1;

        foreach (TableCell cell in grdViewDetails.Rows[e.RowIndex].Cells)
        {
            if (cell.Controls[0] is TextBox)
            {
                TextBox textbox = (TextBox)cell.Controls[0];
                string value = textbox.Text;
            }
            else
            {
                if (cell.Controls[0] is CheckBox)
                {
                    CheckBox chkBoxWeek = (CheckBox)cell.Controls[0];
                    Boolean checkStatus = chkBoxWeek.Checked;
                }
            }
        }

Upvotes: 1

Views: 17783

Answers (2)

Tejas
Tejas

Reputation: 467

Row Editing: When user clicks on edit button and row editing event of grid view will be executed.This event will provide row index

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        databind();
    }

Row Updating: This will perform post back,row-updating event procedure of grid view will be executed

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        Label l = (Label)GridView1.Rows[e.RowIndex].FindControl("Label1");
        TextBox t1 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox1");
        TextBox t2 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox2");
        FileUpload fu = (FileUpload)GridView1.Rows[e.RowIndex].FindControl("FileUpload1");

        string fpath = Server.MapPath("images");
        string fname = fu.FileName;
        string concat = fpath + "\\" + fname;
        fu.SaveAs(concat);

        cmd = new SqlCommand("update userdata set username='" + t1.Text + "', password='" + t2.Text + "' , Image = '" + "~/images/"+ fu.FileName + "' where userid='" + Convert.ToInt32(l.Text) + "'", con);

        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
        GridView1.EditIndex = -1;
        databind();
    }

Upvotes: 2

Freelancer
Freelancer

Reputation: 9074

Row Editing: When user clicks on edit button post backtakes place,row editing event of grid view will be executed.This event will provide row index

protected void gremp_rowediting(object sender,EventArgs e)
 {
   dataset ds=(dstaset)session["ds1"];
   gvemp.editindex=e.new editindex;
//e.newedit index:- will be provide index of row for which edit button is selected
   gvemp.Datasource=Ds.Table["employee"];
   gvemp.Databind();
 }

Row Updating: This will perform post back,row-updating event procedure of grid view will be executed

protected void gvemp-rowupdating(Object sender,EvenArgs e)
 {
  Textbox txt=(Textbox)gvemp.Rows[e.RowIndex].cells[3].controls[0];
 //here i will update the third cell data in grid view
  int avg=int.parse(txt.Text);
  Dataset ds=(dataset)session["ds1"]; 
  ds.Tables["employee"].rows[e.Rowindex]["Average"]=avg;
  ds.Tables["employee"].AcceptChanges();
  session["Ds1"]=ds;
//it will overwrite the session of Dataset
//Rearrange Gridview
  gvemp.editIndex=-1;
  gvemp.Datasource=Ds.Tables["employee"];
  gvemp.DataBind();
 }

Follow this link for more details:

http://www.aspdotnet-sharepoint.com/2011/11/row-editdeleteupdate-in-grid-view-using.html

Upvotes: 1

Related Questions