How retrieve data from a Data Gridview
How do you retrieve data from a gridview and save into database?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Satyapriya NayakPosted Sep 8, 2011, 12:14 PM
Here is your solution
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
using System;
using System.Configuration;
using System.Data;
using System.Linq;
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;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
string connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlDataAdapter ad = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand();
DataTable dataTable;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillstudentGrid();
}
}
private void FillstudentGrid()
{
SqlConnection conn = new SqlConnection(connStr);
dataTable = new DataTable();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM student";
ad = new SqlDataAdapter(cmd);
ad.Fill(dataTable);
ResultGridView.DataSource = dataTable;
ResultGridView.DataBind();
}
protected void ResultGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
ResultGridView.PageIndex = e.NewPageIndex;
FillstudentGrid();
}
protected void ResultGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("AddNew"))
{
TextBox txtFName = (TextBox)ResultGridView.FooterRow.FindControl("txtFName1");
TextBox txtLName = (TextBox)ResultGridView.FooterRow.FindControl("txtLName1");
SqlConnection conn = new SqlConnection(connStr);
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO student(firstname,lastname) Values('" + txtFName.Text + "', '" + txtLName.Text + "')";
conn.Open();
cmd.ExecuteNonQuery();
FillstudentGrid();
conn.Close();
}
}
}
Thanks
If this post helps you mark it as answer
Andile ChokoPosted Sep 8, 2011, 4:06 PM
I wanted to save contacts that i have imported from gmail which i displayed on a gridview to database.
Dipal ChoksiPosted Sep 8, 2011, 1:16 PM
The previous posters have provided very helpful solutions
while I considered what you were looking for, was wondering what was the requirement/objective - could you share some details on that? the best approach can be determined based on what you really need to do..
Mayur DighePosted Sep 8, 2011, 11:49 AM
or
or want to copy all data from GridView , Then
You do this by putting GridView's DataSource into DataTable and then using DataSet's UpdateCommand() method you can save this data into DataBase.
Vijay YadavPosted Sep 8, 2011, 11:27 AM