my .aspx page is
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default9.aspx.cs" Inherits="Default9" %>
and my .aspx.cs code is
using System;
using System.Collections;
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.Collections.Specialized;
using System.Text;
using System.Data.SqlClient;
public partial class Default9 : System.Web.UI.Page
{
private const string SP_GET_ALL_CHORES = "SELECT * FROM employee1";
private void SetInitialRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
dt.Columns.Add(new DataColumn("Column2", typeof(string)));
dt.Columns.Add(new DataColumn("Column3", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dr["Column3"] = string.Empty;
dt.Rows.Add(dr);
//dr = dt.NewRow();
//Store the DataTable in ViewState
ViewState["CurrentTable"] = dt;
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
private void AddNewRowToGrid()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the TextBox values
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
drCurrentRow["Column1"] = box1.Text;
drCurrentRow["Column2"] = box2.Text;
drCurrentRow["Column3"] = box3.Text;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
//Set Previous Data on Postbacks
SetPreviousData();
}
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 1; i < dt.Rows.Count; i++)
{
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
box1.Text = dt.Rows[i]["Column1"].ToString();
box2.Text = dt.Rows[i]["Column2"].ToString();
box3.Text = dt.Rows[i]["Column3"].ToString();
rowIndex++;
}
}
// ViewState["CurrentTable"] = dt;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
SetInitialRow();
}
}
private void BindData()
{
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlCommand ad = new SqlCommand(SP_GET_ALL_CHORES, myConnection);
SqlDataAdapter sqlda = new SqlDataAdapter(ad);
DataTable dt = new DataTable();
sqlda.Fill(dt);
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
private string ConnectionString
{
get
{
return @"data source=hobvision03; initial catalog=master; user id=sa; password=hobvision";
}
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
protected void Button1_Click(object sender, EventArgs e)
{
int rowIndex = 0;
StringCollection sc = new StringCollection();
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the TextBox values
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
//get the values from the TextBoxes
//then add it to the collections with a comma "," as the delimited values
sc.Add(box1.Text + "," + box2.Text + "," + box3.Text);
rowIndex++;
}
//Call the method for executing inserts
InsertRecords(sc);
}
}
}
//A method that returns a string which calls the connection string from the web.config
private string GetConnectionString()
{
//"DBConnection" is the name of the Connection String
//that was set up from the web.config file
return System.Configuration.ConfigurationManager.ConnectionStrings["masterConnectionString"].ConnectionString;
}
//A method that Inserts the records to the database
private void InsertRecords(StringCollection sc)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
StringBuilder sb = new StringBuilder(string.Empty);
string[] splitItems = null;
foreach (string item in sc)
{
const string sqlStatement = "INSERT INTO employee1 (firstname,lastname,id) VALUES";
if (item.Contains(","))
{
splitItems = item.Split(",".ToCharArray());
sb.AppendFormat("{0}('{1}','{2}','{3}'); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2]);
}
}
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sb.ToString(), conn);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
// Hide the Remove Button at the last row of the GridView
protected void Gridview1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
LinkButton lb = (LinkButton)e.Row.FindControl("LinkButton1");
if (lb != null)
{
if (dt.Rows.Count > 1)
{
if (e.Row.RowIndex == dt.Rows.Count - 1)
{
lb.Visible = false;
}
}
else
{
lb.Visible = false;
}
}
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
LinkButton lb = (LinkButton)sender;
GridViewRow gvRow = (GridViewRow)lb.NamingContainer;
int rowID = gvRow.RowIndex + 1;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 1)
{
if (gvRow.RowIndex < dt.Rows.Count - 1)
{
//Remove the Selected Row data
dt.Rows.Remove(dt.Rows[rowID]);
}
}
//Store the current data in ViewState for future reference
ViewState["CurrentTable"] = dt;
//Re bind the GridView for the updated data
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
//Set Previous Data on Postbacks
SetPreviousData();
}
}
please help me regarding this.
AshwiniPosted Nov 7, 2011, 12:27 AM
I have sent my code through attached file please find the attachment.
In this in Default2.aspx page in each row i have used Delete link button this working fine for me but instead of this in each row i used checkboxes and only one Delete button. user will select the checkboxes and clicks on Delete button so that many rows get deleted but this part is not working for me. After selecting checkbox and clicks on delete button the the data is not getting deleted please help me regarding this, i am not getting what is the problem.
Suthish NairPosted Nov 6, 2011, 9:57 AM
TulasiPosted Nov 4, 2011, 8:08 AM
I noted some points
1) ViewState["CurrentTable"] assained in SetInitialRow() method . but ur using
this ViewState["CurrentTable"] in GridviewRowcreatedevent so that it is giving that error becoz viewstate contains null values(is not at intialized before)
2) ur specfing column names in source code of gridview(RowNumber,Lname,Fname,id) but ur creating datatable (RowNumber,Coloumn1,column2,column3)with different coloumn names and Binding this to gridview with different coloumn names ..
Dhaval PatelPosted Nov 4, 2011, 7:24 AM
changes only database table or query and column name
using System;
using System.Collections;
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.Collections.Specialized;
using System.Text;
using System.Data.SqlClient;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
SetInitialRow();
}
}
private const string SP_GET_ALL_CHORES = "SELECT * FROM employee1";
private void SetInitialRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
//dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dt.Columns.Add(new DataColumn("fname", typeof(string)));
dt.Columns.Add(new DataColumn("lname", typeof(string)));
//dt.Columns.Add(new DataColumn("Column3", typeof(string)));
dr = dt.NewRow();
//dr["RowNumber"] = 1;
dr["fname"] = string.Empty;
dr["lname"] = string.Empty;
//dr["Column3"] = string.Empty;
dt.Rows.Add(dr);
//dr = dt.NewRow();
//Store the DataTable in ViewState
ViewState["CurrentTable"] = dt;
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
private void AddNewRowToGrid()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the TextBox values
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
drCurrentRow = dtCurrentTable.NewRow();
//drCurrentRow["RowNumber"] = i + 1;
drCurrentRow["fname"] = box1.Text;
drCurrentRow["lname"] = box2.Text;
//drCurrentRow["Column3"] = box3.Text;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
//Set Previous Data on Postbacks
SetPreviousData();
}
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 1; i < dt.Rows.Count; i++)
{
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
box1.Text = dt.Rows[i]["fname"].ToString();
box2.Text = dt.Rows[i]["lname"].ToString();
//box3.Text = dt.Rows[i]["Column3"].ToString();
rowIndex++;
}
}
// ViewState["CurrentTable"] = dt;
}
}
private void BindData()
{
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlCommand ad = new SqlCommand(SP_GET_ALL_CHORES, myConnection);
SqlDataAdapter sqlda = new SqlDataAdapter(ad);
DataTable dt = new DataTable();
sqlda.Fill(dt);
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
private string ConnectionString
{
get
{
return @"data source=hobvision03; initial catalog=master; user id=sa; password=hobvision";
}
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
protected void Button1_Click(object sender, EventArgs e)
{
int rowIndex = 0;
StringCollection sc = new StringCollection();
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the TextBox values
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
//get the values from the TextBoxes
//then add it to the collections with a comma "," as the delimited values
//sc.Add(box1.Text + "," + box2.Text + "," + box3.Text);
sc.Add(box1.Text + "," + box2.Text);
rowIndex++;
}
//Call the method for executing inserts
InsertRecords(sc);
}
}
}
//A method that returns a string which calls the connection string from the web.config
private string GetConnectionString()
{
//"DBConnection" is the name of the Connection String
//that was set up from the web.config file
//return System.Configuration.ConfigurationManager.ConnectionStrings["masterConnectionString"].ConnectionString;
return ConnectionString;
}
//A method that Inserts the records to the database
private void InsertRecords(System.Collections.Specialized.StringCollection sc)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
StringBuilder sb = new StringBuilder(string.Empty);
string[] splitItems = null;
foreach (string item in sc)
{
const string sqlStatement = "INSERT INTO employee1(fname,lname) VALUES ";
if (item.Contains(","))
{
splitItems = item.Split(",".ToCharArray());
sb.AppendFormat("('{1}','{2}')", sqlStatement, splitItems[0], splitItems[1]);
//sb.AppendFormat("('{1}','{2}')",sqlStatement,splitItems[0], splitItems[1]);
//sb.AppendFormat("{0}('{1}','{2}','{3}'); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2]);
}
}
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sb.ToString(), conn);
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO employee1(fname,lname) VALUES " + sb.ToString();
cmd.ExecuteNonQuery();
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
// Hide the Remove Button at the last row of the GridView
//protected void Gridview1_RowCreated(object sender, GridViewRowEventArgs e)
//{
// if (e.Row.RowType == DataControlRowType.DataRow)
// {
// DataTable dt = (DataTable)ViewState["CurrentTable"];
// LinkButton lb = (LinkButton)e.Row.FindControl("LinkButton1");
// if (lb != null)
// {
// if (dt.Rows.Count > 1)
// {
// if (e.Row.RowIndex == dt.Rows.Count - 1)
// {
// lb.Visible = false;
// }
// }
// else
// {
// lb.Visible = false;
// }
// }
// }
//}
protected void LinkButton1_Click(object sender, EventArgs e)
{
LinkButton lb = (LinkButton)sender;
GridViewRow gvRow = (GridViewRow)lb.NamingContainer;
int rowID = gvRow.RowIndex + 1;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 1)
{
if (gvRow.RowIndex < dt.Rows.Count - 1)
{
//Remove the Selected Row data
dt.Rows.Remove(dt.Rows[rowID]);
}
}
//Store the current data in ViewState for future reference
ViewState["CurrentTable"] = dt;
//Re bind the GridView for the updated data
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
//Set Previous Data on Postbacks
SetPreviousData();
}
}
This post help you then mark as "Accepted Answer"