I have a Gridview with 3 columns and I am adding empty row with the help of 'ADD' button. Now I am trying to insert the data entered in grid to my table. here is my code.
SqlConnection con = new SqlConnection(ConfigurationManager
.ConnectionStrings["gridconnection"]
.ConnectionString);
public 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);
//Store the DataTable in ViewState
ViewState["CurrentTable"] = dt;
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
public 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;
dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
dtCurrentTable.Rows[i - 1]["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();
}
protected void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; 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++;
}
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SetInitialRow();
}
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
protected void ButtonAdd_Click1(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataRow dr = null;
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();
string consString = ConfigurationManager.ConnectionStrings["gridconnection"]
.ConnectionString;
using (SqlConnection connection = new SqlConnection(consString))
{
connection.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
{
//foreach (DataColumn c in dt.Columns)
// // bulkCopy.ColumnMappings.Add(c.Column1, c.Column2, c.Column3);
bulkCopy.DestinationTableName = "GridExcel";
//bulkCopy.ColumnMappings.Add(Column1, c.Column2, c.Column3);
SqlBulkCopyColumnMapping Column =
new SqlBulkCopyColumnMapping("Column1", "Column1");
bulkCopy.ColumnMappings.Add(Column);
SqlBulkCopyColumnMapping Column2nd =
new SqlBulkCopyColumnMapping("Column2", "Column2");
bulkCopy.ColumnMappings.Add(Column2nd);
SqlBulkCopyColumnMapping Column3rd =
new SqlBulkCopyColumnMapping("Column3", "Column3");
bulkCopy.ColumnMappings.Add(Column3rd);
try
{
bulkCopy.WriteToServer(dt);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
GridExcel is my database table name with column names Column1, Column2, Column3. The problem is data is not getting inserted to the table. Please help.
protected void ButtonAdd_Click1(object sender, EventArgs e)
{
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
string consString = ConfigurationManager.ConnectionStrings["gridconnection"]
.ConnectionString;
using (SqlConnection connection = new SqlConnection(consString))
{
connection.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
{
//foreach (DataColumn c in dt.Columns)
// // bulkCopy.ColumnMappings.Add(c.Column1, c.Column2, c.Column3);
bulkCopy.DestinationTableName = "GridExcel";
//bulkCopy.ColumnMappings.Add(Column1, c.Column2, c.Column3);
SqlBulkCopyColumnMapping Column =
new SqlBulkCopyColumnMapping("Column1", "Column1");
bulkCopy.ColumnMappings.Add(Column);
SqlBulkCopyColumnMapping Column2nd =
new SqlBulkCopyColumnMapping("Column2", "Column2");
bulkCopy.ColumnMappings.Add(Column2nd);
SqlBulkCopyColumnMapping Column3rd =
new SqlBulkCopyColumnMapping("Column3", "Column3");
bulkCopy.ColumnMappings.Add(Column3rd);
try
{
bulkCopy.WriteToServer(dt);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
}
}
i am not familiar with ASP.Net but updated your ButtonAdd_Click1, this might fix your issue, this is working fine and fix your issue please do check this
Related
I am using this code to delete rows from grid view and the rows are getting deleted but when I add a new row to my Grid view the deleted row comes back again any suggestions what should I do to delete row from my grid view and I am not using database on it. Thanks in Advance.
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("EmpId", typeof(string)));
dt.Columns.Add(new DataColumn("EmpName", typeof(string)));
dt.Columns.Add(new DataColumn("DeptName", typeof(string)));
dt.Columns.Add(new DataColumn("EmpAddress", typeof(string)));
dt.Columns.Add(new DataColumn("EmpSalary", typeof(string)));
string Id = string.Empty;
string Name = string.Empty;
string DeptName = string.Empty;
string EmpAddress = string.Empty;
string EmpSalary = string.Empty;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridViewRow row = (GridViewRow)GridView1.Rows[i];
if (i != e.RowIndex)
{
Id = row.Cells[1].Text;
Name = row.Cells[2].Text;
DeptName = row.Cells[3].Text;
EmpAddress = row.Cells[4].Text;
EmpSalary = row.Cells[5].Text;
DataRow dr = dt.NewRow();
dr["EmpId"] = Id;
dr["EmpName"] = Name;
dr["DeptName"] = DeptName;
dr["EmpAddress"] = EmpAddress;
dr["EmpSalary"] = EmpSalary;
dt.Rows.Add(dr);
}
}
GridView1.EditIndex = -1;
GridView1.DataBind();
GridView1.DataSource = dt;
}
My add to row code is this
private void AddNewRecordRowToGrid()
{
// check view state is not null
if (ViewState["EmployeeDetails"] != null)
{
//get datatable from view state
DataTable dtCurrentTable = (DataTable)ViewState["EmployeeDetails"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//add each row into data table
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["EmpId"] = txtEmpId.Text;
drCurrentRow["EmpName"] = txtEmpName.Text;
drCurrentRow["DeptName"] = txtDeptName.Text;
drCurrentRow["EmpAddress"] = txtEmpAddress.Text;
drCurrentRow["EmpSalary"] = txtEmpSalary.Text;
}
//Remove initial blank row
if (dtCurrentTable.Rows[0][0].ToString() == "")
{
dtCurrentTable.Rows[0].Delete();
dtCurrentTable.AcceptChanges();
}
//add created Rows into dataTable
dtCurrentTable.Rows.Add(drCurrentRow);
//Bind Gridview with latest Row
GridView1.DataSource = dtCurrentTable;
GridView1.DataBind();
}
}
}
Since you load the employees after adding from your ViewState
DataTable dtCurrentTable = (DataTable)ViewState["EmployeeDetails"];
the deleted row wasn't deleted there. I would suggest to edit the DataTable in your ViewState
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
if (ViewState["EmployeeDetails"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["EmployeeDetails"];
dtCurrentTable.Rows.RemoveAt(e.RowIndex);
ViewState["EmployeeDetails"] = dtCurrentTable;
GridView1.EditIndex = -1;
GridView1.DataBind();
GridView1.DataSource = dtCurrentTable;
}
}
and
private void AddNewRecordRowToGrid()
{
if (ViewState["EmployeeDetails"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["EmployeeDetails"];
DataRow drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["EmpId"] = txtEmpId.Text;
drCurrentRow["EmpName"] = txtEmpName.Text;
drCurrentRow["DeptName"] = txtDeptName.Text;
drCurrentRow["EmpAddress"] = txtEmpAddress.Text;
drCurrentRow["EmpSalary"] = txtEmpSalary.Text;
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["EmployeeDetails"] = dtCurrentTable;
GridView1.DataSource = dtCurrentTable;
GridView1.DataBind();
}
}
I have created dynamic textboxs and dropdownlist in gridview. It is working perfectly. Further I want to fire event in dynamic dropdownlist and do some action.
private ArrayList GetDummyData() {
ArrayList arr = new ArrayList();
arr.Add(new ListItem("Item1", "1"));
arr.Add(new ListItem("Item2", "2"));
arr.Add(new ListItem("Item3", "3"));
arr.Add(new ListItem("Item4", "4"));
arr.Add(new ListItem("Item5", "5"));
return arr;
}
private void FillDropDownList(DropDownList ddl) {
ArrayList arr = GetDummyData();
foreach (ListItem item in arr) {
ddl.Items.Add(item);
}
}
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)));//for TextBox value
dt.Columns.Add(new DataColumn("Column2", typeof(string)));//for TextBox value
dt.Columns.Add(new DataColumn("Column3", typeof(string)));//for DropDownList selected item
dt.Columns.Add(new DataColumn("Column4", typeof(string)));//for DropDownList selected item
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dt.Rows.Add(dr);
//Store the DataTable in ViewState for future reference
ViewState["CurrentTable"] = dt;
//Bind the Gridview
Gridview1.DataSource = dt;
Gridview1.DataBind();
//After binding the gridview, we can then extract and fill the DropDownList with Data
DropDownList ddl1 = (DropDownList)Gridview1.Rows[0].Cells[3].FindControl("DropDownList1");
DropDownList ddl2 = (DropDownList)Gridview1.Rows[0].Cells[4].FindControl("DropDownList2");
FillDropDownList(ddl1);
FillDropDownList(ddl2);
}
private void AddNewRowToGrid() {
if (ViewState["CurrentTable"] != null) {
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0) {
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = dtCurrentTable.Rows.Count + 1;
//add new row to DataTable
dtCurrentTable.Rows.Add(drCurrentRow);
//Store the current data to ViewState for future reference
ViewState["CurrentTable"] = dtCurrentTable;
for (int i = 0; i < dtCurrentTable.Rows.Count - 1; i++) {
//extract the TextBox values
TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("TextBox2");
dtCurrentTable.Rows[i]["Column1"] = box1.Text;
dtCurrentTable.Rows[i]["Column2"] = box2.Text;
//extract the DropDownList Selected Items
DropDownList ddl1 = (DropDownList)Gridview1.Rows[i].Cells[3].FindControl("DropDownList1");
DropDownList ddl2 = (DropDownList)Gridview1.Rows[i].Cells[4].FindControl("DropDownList2");
// Update the DataRow with the DDL Selected Items
dtCurrentTable.Rows[i]["Column3"] = ddl1.SelectedItem.Text;
dtCurrentTable.Rows[i]["Column4"] = ddl2.SelectedItem.Text;
}
//Rebind the Grid with the current data to reflect changes
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 = 0; i < dt.Rows.Count; i++) {
TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("TextBox2");
DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[3].FindControl("DropDownList1");
DropDownList ddl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[4].FindControl("DropDownList2");
//Fill the DropDownList with Data
FillDropDownList(ddl1);
FillDropDownList(ddl2);
if (i < dt.Rows.Count - 1) {
//Assign the value from DataTable to the TextBox
box1.Text = dt.Rows[i]["Column1"].ToString();
box2.Text = dt.Rows[i]["Column2"].ToString();
//Set the Previous Selected Items on Each DropDownList on Postbacks
ddl1.ClearSelection();
ddl1.Items.FindByText(dt.Rows[i]["Column3"].ToString()).Selected = true;
ddl2.ClearSelection();
ddl2.Items.FindByText(dt.Rows[i]["Column4"].ToString()).Selected = true;
}
rowIndex++;
}
}
}
}
protected void Page_Load(object sender, EventArgs e) {
if (!Page.IsPostBack) {
SetInitialRow();
}
}
protected void ButtonAdd_Click(object sender, EventArgs e) {
AddNewRowToGrid();
}
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;
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 and reset row number
dt.Rows.Remove(dt.Rows[rowID]);
ResetRowID(dt);
}
}
//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();
}
private void ResetRowID(DataTable dt) {
int rowNumber = 1;
if (dt.Rows.Count > 0) {
foreach (DataRow row in dt.Rows) {
row[0] = rowNumber;
rowNumber++;
}
}
}
Might be a duplicate of question:
how to add an OnClick event on DropDownList's ListItem that is added dynamically?
Please check the answer given there.
DropDownList changesList = new DropDownList();
ListItem item;
item = new ListItem();
item.Text = "go to google.com";
item.Value = "http://www.google.com";
changesList.Items.Add(item);
changesList.Attributes.Add("onChange", "location.href = this.options[this.selectedIndex].value;");
Also have you tried adding a handler to the event SelectedIndexChanged dynamically when adding the new row to the grid?
I have a strange problem with my code
I can't add row because NullReferenceException in my gridview after delete a row.
My logic is when Add new row, i have the other function to SetPreviousData.
When I didn't delete a row, my SetPreviousData is don't raise any exception, but when after deleting a row and create new row, my SetPreviousData raise a exception that NullReferenceException.
This is my code for 'AddNewRow()'
private void AddNewRowToGrid()
{
if (ViewState["vsCurrent"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["vsCurrent"];
DataRow drNewRow = dtCurrentTable.NewRow();
drNewRow["SALES_SO_LITEM_ID"] = Convert.ToInt32(dtCurrentTable.Rows.Count.ToString()+"101");
drNewRow["ITEM_NAME"] = string.Empty;
drNewRow["QUANTITY"] = 0;
drNewRow["PRICE"] = 0;
dtCurrentTable.Rows.Add(drNewRow);
ViewState["vsCurrent"] = dtCurrentTable;
}
else
{
ViewState["vsCurrent"] = SetInitialRow();
}
BindDataGrid();
SetPreviousData(); //Set Previous Data on Postbacks
}
and this function for SetPreviousData
public void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["vsCurrent"] != null)
{
DataTable dt = (DataTable)ViewState["vsCurrent"];
if (dt.Rows.Count > 0)
{
int max_rowindex = gvDetailSales.Rows.Count - 1;
for (int i = 0; i < dt.Rows.Count; i++)
{
if (dt.Rows[i].RowState != DataRowState.Deleted)
{
Label box1 = (Label)gvDetailSales.Rows[rowIndex].Cells[1].FindControl("lblItemName");
// raise exception because null
Label box2 = (Label)gvDetailSales.Rows[rowIndex].Cells[2].FindControl("lblQuantity");
Label box3 = (Label)gvDetailSales.Rows[rowIndex].Cells[3].FindControl("lblPrice");
box1.Text = dt.Rows[i]["ITEM_NAME"].ToString();
box2.Text = dt.Rows[i]["QUANTITY"].ToString();
box3.Text = dt.Rows[i]["PRICE"].ToString();
rowIndex++;
}
}
}
}
}
How I can handle it ? Thank You
======================EDITED================================================
This is my function for SetInitialRow
public DataTable SetInitialRow()
{
DataTable dtInitial = new DataTable();
DataRow drInitial = null;
dtInitial.Columns.Add(new DataColumn("SALES_SO_LITEM_ID", typeof(string)));
dtInitial.Columns.Add(new DataColumn("ITEM_NAME", typeof(string)));
dtInitial.Columns.Add(new DataColumn("QUANTITY", typeof(int)));
dtInitial.Columns.Add(new DataColumn("PRICE", typeof(float)));
drInitial = dtInitial.NewRow();
drInitial["SALES_SO_LITEM_ID"] = Convert.ToInt32(dtInitial.Rows.Count.ToString() + "101");
drInitial["ITEM_NAME"] = string.Empty;
drInitial["QUANTITY"] = 0;
drInitial["PRICE"] = 0.0;
dtInitial.Rows.Add(drInitial);
return dtInitial;
}
This is my function for BindDataGrid
public void BindDataGrid()
{
gvDetailSales.DataSource = ViewState["vsCurrent"] as DataTable;
gvDetailSales.DataBind();
}
i want to keep adding data in current row of grid unless i press clear button to change row but when ever i start adding data in new added row it creates a new row . I want to hold previous rows . any help !!!
public partial class WebForm5 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!(IsPostBack))
{
Session["List"] = null;
ViewState["i"] = ViewState["j"] = 1;
ViewState["state"] = "";
}
}
public static DataTable dt;
public static int i = 1;
protected void txtName_Click(object sender, EventArgs e)
{
Session["List"] = dt;
dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(int)));
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
if (Convert.ToInt16 (ViewState ["i"]) ==Convert.ToInt16( ViewState["j"]))
{
// here i have to add something
dr = dt.NewRow();
ViewState["state"] = txtName.Text;
dr["RowNumber"] = i;
dr["Column1"] = Convert.ToString(ViewState["state"]) + txtName.Text;
dt.Rows.Add(dr);
}
else if ( Convert .ToInt16 ( ViewState["i"] )!= Convert .ToInt16 ( ViewState["j"]))
{
if (Session["List"] != null)
{
dt = (DataTable)Session["List"];
dr = dt.NewRow();
dr["Column1"] = txtName.Text;
dr["RowNumber"] = i;
ViewState["state"] = txtName.Text;
dt.Rows.Add(dr);
//lst = (List<string>)Session["List"];
//lst.Insert(i,txtAdd.Text);
//i++;
}
ViewState["i"] = ViewState["j"];
}
grdData.DataSource = dt;
grdData.DataBind();
}
protected void btnClr_Click(object sender, EventArgs e)
{
ViewState["j"] = i++;
}
}
public partial class WebForm5 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!(IsPostBack))
{
Session["List"] = null;
ViewState["i"] = ViewState["j"] = 1;
ViewState["state"] = "";
}
}
public static DataTable dt;
public static int i = 1;
protected void txtName_Click(object sender, EventArgs e)
{
Session["List"] = dt;
dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(int)));
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
if (Session["List"] == null)
{
if (Convert.ToInt16(ViewState["i"]) == Convert.ToInt16(ViewState["j"]))
{
dr = dt.NewRow();
dr["RowNumber"] = i;
dr["Column1"] = Convert.ToString(ViewState["state"]) + txtName.Text;
ViewState["state"] = Convert.ToString(ViewState["state"]) + txtName.Text;
dt.Rows.Add(dr);
}
grdData.DataSource = dt;
grdData.DataBind();
}
if (Session["List"] != null)
{
if ( Convert .ToInt16 ( ViewState["i"] )!= Convert .ToInt16 ( ViewState["j"]))
{
dt = (DataTable)Session["List"];
dr = dt.NewRow();
dr["Column1"] = txtName.Text;
dr["RowNumber"] = i;
dt.Rows.Add(dr);
//lst = (List<string>)Session["List"];
//lst.Insert(i,txtAdd.Text);
//i++;
grdData.DataSource = dt;
grdData.DataBind();
}
else if (Convert.ToInt16(ViewState["i"]) == Convert.ToInt16(ViewState["j"]))
{
dt = (DataTable)Session["List"];
ViewState["state"] = grdData.Rows[((grdData.Rows.Count) - 1)].Cells[1].Text;
string i =Convert.ToString( ViewState["state"]);
int j = dt.Rows.Count;
dt.Rows[(dt.Rows.Count)-1]["Column1"] =Convert.ToString(ViewState["state"])+ txtName.Text;
grdData.DataSource = dt;
grdData.DataBind();
}
ViewState["i"] = ViewState["j"];
}
txtName.Text = "";
}
protected void btnClr_Click(object sender, EventArgs e)
{
ViewState["j"] = i++;
ViewState["state"] = "";
// txtName.Text = grdData.Rows[(grdData.Rows.Count - 1)].Cells[1].Text;
}
protected void btnnew_Click(object sender, EventArgs e)
{
dt.Rows[(grdData.Rows.Count - 1)]["Column1"] = txtName.Text;
grdData.DataSource = dt;
grdData.DataBind();
}
}
I have this code here :
private void SetInitialRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("Question", typeof(string)));
dt.Columns.Add(new DataColumn("Answer", typeof(string)));
dr = dt.NewRow();
dr["Question"] = string.Empty;
dr["Answer"] = string.Empty;
dt.Rows.Add(dr);
//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");
drCurrentRow = dtCurrentTable.NewRow();
dtCurrentTable.Rows[i - 1]["Question"] = box1.Text;
dtCurrentTable.Rows[i - 1]["Answer"] = box2.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 = 0; 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");
box1.Text = dt.Rows[i]["Question"].ToString();
box2.Text = dt.Rows[i]["Answer"].ToString();
Session["Question1"] = box1.Text;
rowIndex++;
}
}
}
}
protected void btnAdd_Click1(object sender, EventArgs e)
{
AddNewRowToGrid();
}
And now i have another button call btnCreate . I click the add button to add rows in Grid View , means adding one row and so on every click . After i click create button , i want the rows number back to one , for now , the rows will be stuck at the number of times i click the add button until i refresh the page. I need the number of rows to be reseted to 1 after i have click on the create button .
You can direcly call SetInitialRow() method in your btnCreate click event, that means you are binding a single row to gridview which mean number of rows reseted to 1.
You can add this to the btnAdd_Click1 method:
dtCurrentTable.Rows(1).Selected = True
I have tried your same code and it works in mine.
Like this.
protected void Page_Load(object sender, EventArgs e)
{
SetInitialRow();
}
private void SetInitialRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("Question", typeof(string)));
dt.Columns.Add(new DataColumn("Answer", typeof(string)));
dr = dt.NewRow();
dr["Question"] = string.Empty;
dr["Answer"] = string.Empty;
dt.Rows.Add(dr);
//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[i].FindControl("TextBox1");
TextBox box2 = (TextBox)GridView1.Rows[i].FindControl("TextBox2");
drCurrentRow = dtCurrentTable.NewRow();
dtCurrentTable.Rows[i - 1]["Question"] = box1.Text;
dtCurrentTable.Rows[i - 1]["Answer"] = box2.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 = 0; i < dt.Rows.Count; i++)
{
TextBox box1 = (TextBox)GridView1.Rows[rowIndex].FindControl("TextBox1");
TextBox box2 = (TextBox)GridView1.Rows[rowIndex].FindControl("TextBox2");
box1.Text = dt.Rows[i]["Question"].ToString();
box2.Text = dt.Rows[i]["Answer"].ToString();
Session["Question1"] = box1.Text;
rowIndex++;
}
}
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
protected void prevRow_Click(object sender, EventArgs e)
{
SetPreviousData();
}
I am sory sory if my answer is on wrong track depending on your requirement. Comment and queries are welcome. thank you