GridView overwrite rows - c#

I have a gridview:
<asp:GridView ID="GridView1" runat="server"
ShowFooter="True" AutoGenerateColumns="False" Width="100%" Height="100%">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Nr.">
<ControlStyle BorderStyle="None" />
</asp:BoundField>
<asp:TemplateField HeaderText="Message">
<ItemTemplate>
<asp:TextBox Native="True" ID="txtName" runat="server"></asp:TextBox>
</ItemTemplate>
<ControlStyle BorderStyle="None" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Data">
<ItemTemplate>
<asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
</ItemTemplate>
<ControlStyle BorderStyle="None" />
</asp:TemplateField>
</Columns>
</asp:GridView>
and 2 buttons. When I click each button, a new row is inserted in Gridview.
To create and bind data tot GridView, I have 2 functions:
private void AddNewRow(string s, string s1)
{
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++)
{
TextBox TextBoxName =
(TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txtName");
TextBoxName.Text = s;
TextBox TextBoxAge =
(TextBox)GridView1.Rows[rowIndex].Cells[2].FindControl("txtAge");
TextBoxAge.Text = s1;
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Col1"] = TextBoxName.Text;
dtCurrentTable.Rows[i -1]["Col2"] = TextBoxAge.Text;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
GridView1.DataSource = dtCurrentTable;
GridView1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
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 TextBoxName = (TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txtName");
TextBox TextBoxAge = (TextBox)GridView1.Rows[rowIndex].Cells[2].FindControl("txtAge");
TextBoxName.Text = dt.Rows[i]["Col1"].ToString();
TextBoxAge.Text = dt.Rows[i]["Col2"].ToString();
rowIndex++;
}
}
}
}
When I click on button 1, data is bound and a new row is created:
protected void Button1_Click(object sender, EventArgs e)
{ DateTime data = DateTime.Now;
string dt = data.ToString();
AddNewRow("Start", dt);
}
When I click on button 2, data is bound and a new row is created:
protected void Button2_Click(object sender, EventArgs e)
{ DateTime data = DateTime.Now;
string dt = data.ToString();
AddNewRow("Stop", dt);
}
Let's say that first I click on button 1. Everything is ok. First row contains the message "Start" and the corresponding date. Also a new row is created. If I press button 2, row 2 contains the message "Stop" and the corresponding date, but also first row is overwritten with the message "Stop". What should I do to don't overwrite the first row?

Related

I'm deleting rows from gridview but all data in the table is deleted

I want to add and delete rows dynamically in Gridview. Adding is successful. When I delete the row, the row is deleted successfully. But the data entered in other rows is cleared.
I want to delete rows. I also want to prevent the deletion of previously entered data.
Default.aspx
<asp:GridView ID="Gridview1" runat="server" AutoGenerateColumns="False" OnSelectedIndexChanged="Gridview1_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Header 2">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 3">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 4">
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ControlStyle-CssClass="row-edit" HeaderText="">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" CommandName="Select" runat="server"><i class="fas fa-times"></i></asp:LinkButton>
</ItemTemplate>
<ControlStyle CssClass="row-edit"></ControlStyle>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click" />
Default.aspx.cs
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);
//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;
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();
}
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");
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 Gridview1_SelectedIndexChanged(object sender, EventArgs e)
{
int indis = Gridview1.SelectedIndex;
GridViewRow satir = Gridview1.Rows[indis];
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow[] _row = dtCurrentTable.Select("RowNumber=" + satir.Cells[0].Text);
foreach (DataRow row in _row)
{
row.Delete();
}
dtCurrentTable.AcceptChanges();
ViewState["CurrentTable"] = dtCurrentTable;
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
Here's the problem
(It won't let me paste it as a flat image.)
My problem
Well, we are deleting one row at a time, right?
Ok, based on feedback, need/want this for the markup:
<asp:GridView ID="Gridview1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Header 2">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("Column1") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 3">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Eval("Column2") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 4">
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Eval("Column3") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:Button ID="cmdDel" runat="server" Text="Delete" OnClick="cmdDel_Click"
OnClientClick="return confirm('Delete this row? (cannot undo)');"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click" />
<asp:Button ID="cmdSave" runat="server" Text="Save Grid to Table" Style="margin-left:30px" OnClick="cmdSave_Click"/>
And the code looks like:
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CreateTable();
AddRow();
LoadGrid();
ViewState["MyTable"] = dt;
}
else
{
dt = (DataTable)ViewState["MyTable"];
}
}
void CreateTable()
{
dt.Columns.Add(new DataColumn("RowNumber", typeof(int)));
dt.Columns[0].AutoIncrementSeed = 1;
dt.Columns[0].AutoIncrementStep = 1;
dt.Columns[0].AutoIncrement = true;
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
dt.Columns.Add(new DataColumn("Column2", typeof(string)));
dt.Columns.Add(new DataColumn("Column3", typeof(string)));
}
void AddRow()
{
DataRow dr = dt.NewRow();
dr["Column1"] = "";
dr["Column2"] = "";
dr["Column3"] = "";
dt.Rows.Add(dr);
}
void LoadGrid()
{
// Gridview1.Columns.Clear();
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
SaveData();
AddRow();
LoadGrid();
}
void SaveData()
{
// move grid changes back to table
foreach (GridViewRow gvRow in Gridview1.Rows)
{
//extract the TextBox values
DataRow dr = dt.Rows[gvRow.RowIndex];
dr["Column1"] = ((TextBox)gvRow.FindControl("TextBox1")).Text;
dr["Column2"] = ((TextBox)gvRow.FindControl("TextBox2")).Text;
dr["Column3"] = ((TextBox)gvRow.FindControl("TextBox3")).Text;
}
dt.AcceptChanges();
}
protected void cmdSave_Click(object sender, EventArgs e)
{
SaveData();
}
protected void cmdDel_Click(object sender, EventArgs e)
{
Button cmdDel = (Button)sender;
GridViewRow gvRow = (GridViewRow)cmdDel.Parent.Parent;
dt.Rows[gvRow.RowIndex].Delete();
dt.AcceptChanges();
LoadGrid();
}
Of course the save button in real use would be "submit" and move on to the next web page, or whatever task the user is working on.
And I assume this is just for learning, since a table just sitting in memory has next to zero use. I would assume that the table would be from a database, else this setup not all that much use.

I am creating billing form. In that i added textbox and dropdownlist in gridview. now in textbox1 i want to fetch price from database.

I am creating billing form. In that i added textbox and dropdownlist in gridview. now in textbox1 i want to fetch price from database. so how do i get price in text box1? i tried a lot but i could not find the solution.
<!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></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<div>
<asp:gridview ID="Gridview1" runat="server" ShowFooter="true"
AutoGenerateColumns="false"
OnRowCreated="Gridview1_RowCreated"
>
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Medicine Id" />
<asp:TemplateField HeaderText="Medicine Name">
<ItemTemplate>
<asp:DropDownList ID="DropDownList3" runat="server" AppendDataBoundItems="true">
<asp:ListItem Value="-1">Select</asp:ListItem>
<asp:ListItem>crocin</asp:ListItem>
<asp:ListItem>colgate</asp:ListItem>
<asp:ListItem></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:DropDownList ID="DropDownList4" runat="server" AppendDataBoundItems="true">
<asp:ListItem Value="-1">Select</asp:ListItem>
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
<asp:ListItem></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server"
Text="Add New Row"
onclick="ButtonAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server"
onclick="LinkButton1_Click">Remove</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:gridview>
</div>
<p>
</p>
<asp:TextBox ID="lblMessage" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="BtnSave" />
</form>
</body>
</html>
in cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Data;
using System.Collections.Specialized;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
namespace WebApplication11
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SetInitialRow();
}
}
// 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 DropDownList selected item
dt.Columns.Add(new DataColumn("Column2", typeof(string)));//for DropDownList selected item
dt.Columns.Add(new DataColumn("Column3", typeof(string)));//for TextBox value
dt.Columns.Add(new DataColumn("Column4", typeof(string)));//for TextBox value
dr = dt.NewRow();
dr["RowNumber"] = 1;
// dr["Column3"] = 555;
dr["Column3"] = string.Empty;
dr["Column4"] = 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[1].FindControl("DropDownList3");
DropDownList ddl2 = (DropDownList)Gridview1.Rows[0].Cells[2].FindControl("DropDownList4");
// 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 DropDownList Selected Items
DropDownList ddl1 = (DropDownList)Gridview1.Rows[i].Cells[1].FindControl("DropDownList3");
DropDownList ddl2 = (DropDownList)Gridview1.Rows[i].Cells[2].FindControl("DropDownList4");
// Update the DataRow with the DDL Selected Items
dtCurrentTable.Rows[i]["Column1"] = ddl1.SelectedItem.Text;
dtCurrentTable.Rows[i]["Column2"] = ddl2.SelectedItem.Text;
//extract the TextBox values
TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[3].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[4].FindControl("TextBox2");
dtCurrentTable.Rows[i]["Column3"] = box1.Text;
dtCurrentTable.Rows[i]["Column4"] = box2.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()
{
SqlConnection cnn = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=medical_store_management2;Integrated Security=True");
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");
DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("DropDownList3");
DropDownList ddl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("DropDownList4");
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("TextBox2");
//Fill the DropDownList with Data
// FillDropDownList(ddl1);
// FillDropDownList(ddl2);
if (i < dt.Rows.Count - 1)
{
String sql = ("select price from medicine where med_name='" + ddl1.Text + "'");
cnn.Open();
SqlCommand cmd = new SqlCommand(sql, cnn);
SqlDataReader dr;
dr = cmd.ExecuteReader();
//Set the Previous Selected Items on Each DropDownList on Postbacks
ddl1.ClearSelection();
ddl1.Items.FindByText(dt.Rows[i]["Column1"].ToString()).Selected = true;
ddl2.ClearSelection();
ddl2.Items.FindByText(dt.Rows[i]["Column2"].ToString()).Selected = true;
//Assign the value from DataTable to the TextBox
if (dr.Read())
{
box1.Text = dr.GetValue(0).ToString();
}
cnn.Close();
//box1.Text = dt.Rows[i]["Column3"].ToString();
box2.Text = dt.Rows[i]["Column4"].ToString();
}
rowIndex++;
}
}
}
}
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++;
}
}
}
private void InsertRecords(StringCollection sc)
{
StringBuilder sb = new StringBuilder(string.Empty);
string[] splitItems = null;
const string sqlStatement = "INSERT INTO medsale1 (mname,qty,price,total) VALUES";
foreach (string item in sc)
{
if (item.Contains(","))
{
splitItems = item.Split(",".ToCharArray());
sb.AppendFormat("{0}('{1}','{2}','{3}','{4}'); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2], splitItems[3]);
}
}
using (SqlConnection connection = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=medical_store_management2;Integrated Security=True"))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand(sb.ToString(), connection))
{
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
lblMessage.Text = "Records successfully saved!";
}
protected void BtnSave_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
DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("DropDownList3");
DropDownList ddl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("DropDownList4");
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("TextBox2");
//get the values from TextBox and DropDownList
//then add it to the collections with a comma "," as the delimited values
sc.Add(string.Format("{0},{1},{2},{3}", ddl1.SelectedItem.Text, ddl2.SelectedItem.Text, box1.Text, box2.Text));
// sc.Add(string.Format("{0},{1},{2},{3}", box1.Text, box2.Text, ddl1.SelectedItem.Text, ddl2.SelectedItem.Text));
rowIndex++;
}
//Call the method for executing inserts
InsertRecords(sc);
}
}
}
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
DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("DropDownList3");
DropDownList ddl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("DropDownList4");
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("TextBox2");
// DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[3].FindControl("DropDownList1");
// DropDownList ddl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[4].FindControl("DropDownList2");
//get the values from TextBox and DropDownList
//then add it to the collections with a comma "," as the delimited values
sc.Add(string.Format("{0},{1},{2},{3}", ddl1.SelectedItem.Text, ddl2.SelectedItem.Text, box1.Text, box2.Text));
rowIndex++;
}
//Call the method for executing inserts
InsertRecords(sc);
}
}
}
}
}
You can achieve this by detecting when user choose the medicine name or the quantity. In order to do this just add OnSelectedIndexChanged for your both DropDownLists :
OnSelectedIndexChanged="DropDownList3_SelectedIndexChanged"
OnSelectedIndexChanged="DropDownList4_SelectedIndexChanged"
This event will fire every time you change the selection of the item. You also need to set the AutoPostBack property for both DropDownLists to true, otherwise the events won't fire.
Now your code behind can look like this:
protected void DropDownList3_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList medicineName = (DropDownList)sender;
if (medicineName.SelectedValue != "-1") // if medicine name is selected
{
GridViewRow row = (GridViewRow)medicineName.Parent.Parent; // find row
int quantity = Convert.ToInt32(((DropDownList)row.FindControl("DropDownList4")).SelectedValue); // find Quantity
if (quantity != -1) // if quanity is selected
{
int price = 1; // TODO: here you take the prize from the database by medicine name
price = price * quantity;
TextBox txtPrice = (TextBox)row.FindControl("TextBox1"); // find price textbox for this row
txtPrice.Text = Convert.ToString(price); // assign price value to this textbox
}
}
}
Everytime when user select item in medicine name dropdownlist, method checks if quantity is selected, and if yes you take the price from db, multiply by quantity and assign this value to the textbox. Of course in above example I didn't implement the part when you should take the price from db. Same way you have to implement the event for quanity dropdownlist.

How can i transfer one gridview row to another gridview row in asp.net

I have two grid views :
gvdetails and
gvTranferRows
gvdetails are bind from selected database. The fields are :
id,
moduleName and
Item fields.
In gvTransferRows fields are :
id,
ModuleName,
Item and
BatchNo.
BatchNo is selected from dropdownlist.
But I want to transfer selected rows from gvdetails to gvTranferRows.
In this process I successfully remove and add gvdetails selected rows to gvTranferRows by clicking remove button at same time and vice versa.
But after clicking the remove button it done and again same operation to second time clicking the add button the gvdetails gridview will completely remove it transfer to gvTransferRows.
What I need is to select second time in add button, it will not remove only selected values remove and transfer to second gridview.
This is the code I tried for code :
.aspx:
<table align="center">
<tr>
<td class="auto-style2"></td>
<td class="auto-style1">
<asp:DropDownList ID="ddlbatchno" runat="server" Height="16px" Width="131px">
</asp:DropDownList>
</td>
</tr>
<tr>
<td class="auto-style2"></td>
</tr>
<tr>
<td class="auto-style2" valign="top">
<asp:GridView ID="gvDetails" runat="server" DataKeyNames="ModuleName" AutoGenerateColumns="false" CellPadding="5">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="id" HeaderText="id" />
<asp:BoundField DataField="ModuleName" HeaderText="ModuleName" />
<asp:BoundField DataField="Item" HeaderText="Item" />
<asp:BoundField DataField="BatchNo" HeaderText="BatchNo" />
</Columns>
<HeaderStyle BackColor="#6699ff" Font-Bold="true" ForeColor="White" />
</asp:GridView>
</td>
<td class="auto-style1">
<asp:Button ID="btnAdd" runat="server" OnClick="btnAdd_Click" Text="ADD" />
<br />
<label>
>><br />
<br />
</label>
<br />
<asp:Button ID="btnRemove" runat="server" OnClick="btnRemove_Click" Text="Remove" />
<br />
<label>
<<</label> </td>
<td valign="top">
<asp:GridView ID="gvTranferRows" runat="server" DataKeyNames="ModuleName" AutoGenerateColumns="false" CellPadding="5" EmptyDataText="No Records Found">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect2" runat="server" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="id" HeaderText="id" />
<asp:BoundField DataField="ModuleName" HeaderText="ModuleName" />
<asp:BoundField DataField="Item" HeaderText="Item" />
<asp:BoundField DataField="BatchNo" HeaderText="BatchNo" />
</Columns>
<HeaderStyle BackColor="#6699ff" Font-Bold="true" ForeColor="White" />
</asp:GridView>
<br />
</td>
</tr>
</table>
.cs page:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlbatch();
BindGridview();
BindSecondGrid();
}
}
public void ddlbatch()
{
SqlCommand cmd1 = new SqlCommand("Select BatchNo from Batches", con);
cmd1.CommandType = CommandType.Text;
cmd1.Connection = con;
con.Open();
ddlbatchno.DataSource = cmd1.ExecuteReader();
ddlbatchno.DataTextField = "BatchNo";
ddlbatchno.DataBind();
con.Close();
ddlbatchno.Items.Insert(0, new ListItem("--Select batche no--", "0"));
}
protected void BindGridview() //Binding gvDetaails gridview
{
SqlDataAdapter da = new SqlDataAdapter("select id,ModuleName,Item,BatchNo from ModuleItems", con);
DataTable dt = new DataTable();
da.Fill(dt);
ViewState["dt"] = dt;
ViewState["dt1"] = dt;
gvDetails.DataSource = dt;
gvDetails.DataBind();
}
protected void BindSecondGrid() // binding gvtransfer gridview
{
DataTable dt = (DataTable)ViewState["GetRecords"];
gvTranferRows.DataSource = dt;
gvTranferRows.DataBind();
}
string name;
protected void btnAdd_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in gvDetails.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("chkSelect") as CheckBox);
if (chkRow.Checked)
{
int totalCount = gvDetails.Rows.Cast<GridViewRow>().Count(r => ((CheckBox)r.FindControl("chkSelect")).Checked);
name += row.Cells[1].Text + ",";
}
}
}
string[] name3 = name.Split(',');
for (int l = 0; l < name3.Length; l++)
{
string str = "UPDATE ModuleItems SET BatchNo = " + ddlbatchno.SelectedItem.ToString() + " WHERE id= '" + name3[l] + "'";
SqlCommand cmd = new SqlCommand(str, con);
con.Open();
int j = cmd.ExecuteNonQuery();
con.Close();
}
foreach (GridViewRow oItemLeft in gvDetails.Rows)
{
if (((CheckBox)oItemLeft.FindControl("chkSelect")).Checked)
{
GetSelectedRows();
BindSecondGrid();
break;
}
}
DataTable dt = ViewState["dt"] as DataTable; //2nd time adding gvdetails to gvtransfer dt will become null
if (dt != null)
{
for (int i = dt.Rows.Count - 1; i >= 0; i--)
{
DataRow row = dt.Rows[i];
string dtname = row["id", DataRowVersion.Original].ToString();
string[] name1 = name.Split(',');
for (int l = 0; l < name1.Length; l++)
{
string name2 = name1[l].ToString();
if (dtname == name2)
{
row.Delete();
}
}
}
}
ViewState["dt"] = dt;
gvDetails.DataSource = dt;
gvDetails.DataBind();
}
private void GetSelectedRows()
{
DataTable dt;
if (ViewState["GetRecords"] != null)
dt = (DataTable)ViewState["GetRecords"];
else
dt = CreateTable();
for (int i = 0; i < gvDetails.Rows.Count; i++)
{
CheckBox chk = (CheckBox)gvDetails.Rows[i].Cells[0].FindControl("chkSelect");
if (chk.Checked)
{
dt = AddGridRow(gvDetails.Rows[i], dt);
}
}
ViewState["GetRecords"] = dt;
}
private DataTable CreateTable()
{
DataTable dt = new DataTable();
dt.Columns.Add("id");
dt.Columns.Add("ModuleName");
dt.Columns.Add("Item");
dt.Columns.Add("BatchNo");
dt.AcceptChanges();
return dt;
}
private DataTable AddGridRow(GridViewRow gvRow, DataTable dt)
{
DataRow[] dr = dt.Select("id = '" + gvRow.Cells[1].Text + "'");
if (dr.Length <= 0)
{
dt.Rows.Add();
int rowscount = dt.Rows.Count - 1;
dt.Rows[rowscount]["id"] = gvRow.Cells[1].Text;
dt.Rows[rowscount]["ModuleName"] = gvRow.Cells[2].Text;
dt.Rows[rowscount]["Item"] = gvRow.Cells[3].Text;
dt.Rows[rowscount]["BatchNo"] = ddlbatchno.SelectedItem.Text;
dt.AcceptChanges();
}
return dt;
}
protected void btnRemove_Click(object sender, EventArgs e)
{
if (gvTranferRows.Rows.Count > 0)
{
foreach (GridViewRow row in gvTranferRows.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow1 = (row.Cells[0].FindControl("chkSelect2") as CheckBox);
if (chkRow1.Checked)
{
int totalCount = gvTranferRows.Rows.Cast<GridViewRow>().Count(r => ((CheckBox)r.FindControl("chkSelect2")).Checked);
name += row.Cells[1].Text + ",";
}
}
}
string[] name3 = name.Split(',');
foreach (GridViewRow oItemLeft in gvTranferRows.Rows)
{
if (((CheckBox)oItemLeft.FindControl("chkSelect2")).Checked)
{
GetRemoveRows();
BindGridview();
//break;
}
}
DataTable dt = ViewState["dt"] as DataTable;
for (int i = dt.Rows.Count - 1; i >= 0; i--)
{
DataRow row = dt.Rows[i];
string dtname = row["id", DataRowVersion.Original].ToString();
string[] name1 = name.Split(',');
for (int l = 0; l < name1.Length; l++)
{
string name2 = name1[l].ToString();
if (dtname != name2)
{
row.Delete();
}
}
}
ViewState["dt"] = dt;
gvTranferRows.DataSource = dt;
gvTranferRows.DataBind();
}
}
DataTable dt,dt1;
private void GetRemoveRows()
{
if (ViewState["GetRecords"] != null)
dt = (DataTable)ViewState["GetRecords"];
ViewState["GetRecords"] = dt;
ViewState["GetRecords2"] = dt;
gvDetails.DataSource = dt;
gvDetails.DataBind();
this. ViewState.Remove("GetRecords2"); //for viewstate control
ViewState["GetRecords2"] = null;//for variables
}
I am attaching my result image how the result will process. I posted full of my code can anyone please help me out.
use a temporary DataTable to maintain the list selected rows or records and then use the DataTable to bind the secondary GridView.
U will get more idea from here
Transfer Selected Rows from one GridView to Another in Asp.net
Another way to transfer data
Please try DataTable.ImportRow method:
DataTable.ImportRow() on MSDN
I'm using this method on many WebForms and MVC pages and it works great.

How to set different ids for each control in each gridview row

I have a GridView with columns manually defined. I have several rows (I use a button to add a row). My problem is that all controls in the same column have the same id, and thus I can't use JQuery Datepicker for my Date column (called Fecha).
I believe I can get the add a row button to work (keeping old data) with control ids like txtFecha1, txtFecha2, etc. But where should I set those names?
I should mention I would also settle for a way to make JQuery datepicker work on controls with the same id, but many answers state that it won't work, since datepicker is asuming that I'm a good programmer and I set a different id for every control.
Code for the GridView:
<asp:GridView CssClass="table table-striped table-bordered table-condensed"
ID="gvActividades" runat="server" EmptyDataText="Error" AllowPaging="False"
AutoGenerateColumns="false" OnRowDataBound="gvActividades_OnRowDataBound"
OnRowDeleting="gvActividades_RowDeleting">
<Columns>
<asp:CommandField ShowDeleteButton="True" />
<asp:TemplateField runat="server" HeaderText="Técnico">
<ItemTemplate>
<asp:DropDownList runat="server" ClientIDMode="Static" class="form-control" ID="cboTecnico">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField runat="server" HeaderText="Fecha">
<ItemTemplate>
<asp:TextBox runat="server" ClientIDMode="Static" class="form-control datepicker" ID="txtFecha" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField runat="server" HeaderText="Hora de inicio">
<ItemTemplate>
<asp:TextBox runat="server" ClientIDMode="Static" class="form-control" ID="txtHoraInicio" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField runat="server" HeaderText="Hora de fin">
<ItemTemplate>
<asp:TextBox runat="server" ClientIDMode="Static" class="form-control" ID="txtHoraFin" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField runat="server" HeaderText="Repuesto">
<ItemTemplate>
<asp:DropDownList runat="server" ClientIDMode="Static" class="form-control" ID="cboRepuesto">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField runat="server" HeaderText="Cantidad">
<ItemTemplate>
<asp:TextBox runat="server" ClientIDMode="Static" class="form-control" ID="txtCantidad" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField runat="server" HeaderText="Descripción">
<ItemTemplate>
<asp:TextBox runat="server" ClientIDMode="Static" class="form-control" ID="txtDescripcion" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<SelectedRowStyle CssClass="gvSelectedRowStyle" />
<PagerStyle CssClass="gvPagerStyle" />
</asp:GridView>
Code for the add a row button (the method called when pressing the button):
protected void cmdAgregarFila_Click(object sender, EventArgs e)
{
if (null == ViewState["CurrentTable"])
{
return;
}
int rowIndex = 0;
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
DropDownList cboTecnico =
(DropDownList)gvActividades.Rows[rowIndex].Cells[1].FindControl("cboTecnico");
TextBox txtFecha =
(TextBox)gvActividades.Rows[rowIndex].Cells[2].FindControl("txtFecha");
TextBox txtHoraInicio =
(TextBox)gvActividades.Rows[rowIndex].Cells[3].FindControl("txtHoraInicio");
TextBox txtHoraFin =
(TextBox)gvActividades.Rows[rowIndex].Cells[4].FindControl("txtHoraFin");
DropDownList cboRepuesto =
(DropDownList)gvActividades.Rows[rowIndex].Cells[5].FindControl("cboRepuesto");
TextBox txtCantidad =
(TextBox)gvActividades.Rows[rowIndex].Cells[6].FindControl("txtCantidad");
TextBox txtDescripcion =
(TextBox)gvActividades.Rows[rowIndex].Cells[7].FindControl("txtDescripcion");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Col1"] = cboTecnico.SelectedValue;
dtCurrentTable.Rows[i - 1]["Col2"] = txtFecha.Text;
dtCurrentTable.Rows[i - 1]["Col3"] = txtHoraInicio.Text;
dtCurrentTable.Rows[i - 1]["Col4"] = txtHoraFin.Text;
dtCurrentTable.Rows[i - 1]["Col5"] = cboRepuesto.SelectedValue;
dtCurrentTable.Rows[i - 1]["Col6"] = txtCantidad.Text;
dtCurrentTable.Rows[i - 1]["Col7"] = txtDescripcion.Text;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
gvActividades.DataSource = dtCurrentTable;
gvActividades.DataBind();
}
SetPreviousData();
}
Other methods for the row-adding to work:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
FirstGridViewRow();
}
}
private void FirstGridViewRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dt.Columns.Add(new DataColumn("Col1", typeof(string)));
dt.Columns.Add(new DataColumn("Col2", typeof(string)));
dt.Columns.Add(new DataColumn("Col3", typeof(string)));
dt.Columns.Add(new DataColumn("Col4", typeof(string)));
dt.Columns.Add(new DataColumn("Col5", typeof(string)));
dt.Columns.Add(new DataColumn("Col6", typeof(string)));
dt.Columns.Add(new DataColumn("Col7", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Col1"] = string.Empty;
dr["Col2"] = string.Empty;
dr["Col3"] = string.Empty;
dr["Col4"] = string.Empty;
dr["Col5"] = string.Empty;
dr["Col6"] = string.Empty;
dr["Col7"] = string.Empty;
dt.Rows.Add(dr);
ViewState["CurrentTable"] = dt;
gvActividades.DataSource = dt;
gvActividades.DataBind();
}
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++)
{
DropDownList cboTecnico =
(DropDownList)gvActividades.Rows[rowIndex].Cells[1].FindControl("cboTecnico");
TextBox txtFecha =
(TextBox)gvActividades.Rows[rowIndex].Cells[2].FindControl("txtFecha");
TextBox txtHoraInicio =
(TextBox)gvActividades.Rows[rowIndex].Cells[3].FindControl("txtHoraInicio");
TextBox txtHoraFin =
(TextBox)gvActividades.Rows[rowIndex].Cells[4].FindControl("txtHoraFin");
DropDownList cboRepuesto =
(DropDownList)gvActividades.Rows[rowIndex].Cells[5].FindControl("cboRepuesto");
TextBox txtCantidad =
(TextBox)gvActividades.Rows[rowIndex].Cells[6].FindControl("txtCantidad");
TextBox txtDescripcion =
(TextBox)gvActividades.Rows[rowIndex].Cells[7].FindControl("txtDescripcion");
cboTecnico.SelectedValue = dt.Rows[i]["Col1"].ToString();
txtFecha.Text = dt.Rows[i]["Col2"].ToString();
txtHoraInicio.Text = dt.Rows[i]["Col3"].ToString();
txtHoraFin.Text = dt.Rows[i]["Col4"].ToString();
cboRepuesto.SelectedValue = dt.Rows[i]["Col5"].ToString();
txtCantidad.Text = dt.Rows[i]["Col6"].ToString();
txtDescripcion.Text = dt.Rows[i]["Col7"].ToString();
rowIndex++;
}
}
}
}
protected void gvActividades_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
SetRowData();
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
int rowIndex = Convert.ToInt32(e.RowIndex);
if (dt.Rows.Count > 1)
{
dt.Rows.Remove(dt.Rows[rowIndex]);
drCurrentRow = dt.NewRow();
ViewState["CurrentTable"] = dt;
gvActividades.DataSource = dt;
gvActividades.DataBind();
SetPreviousData();
//actualizarTotal();
}
}
}
private void SetRowData()
{
int rowIndex = 0;
if (null == ViewState["CurrentTable"])
{
return;
}
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
DropDownList cboTecnico =
(DropDownList)gvActividades.Rows[rowIndex].Cells[1].FindControl("cboTecnico");
TextBox txtFecha =
(TextBox)gvActividades.Rows[rowIndex].Cells[2].FindControl("txtFecha");
TextBox txtHoraInicio =
(TextBox)gvActividades.Rows[rowIndex].Cells[3].FindControl("txtHoraInicio");
TextBox txtHoraFin =
(TextBox)gvActividades.Rows[rowIndex].Cells[4].FindControl("txtHoraFin");
DropDownList cboRepuesto =
(DropDownList)gvActividades.Rows[rowIndex].Cells[5].FindControl("cboRepuesto");
TextBox txtCantidad =
(TextBox)gvActividades.Rows[rowIndex].Cells[6].FindControl("txtCantidad");
TextBox txtDescripcion =
(TextBox)gvActividades.Rows[rowIndex].Cells[7].FindControl("txtDescripcion");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Col1"] = cboTecnico.SelectedValue;
dtCurrentTable.Rows[i - 1]["Col2"] = txtFecha.Text;
dtCurrentTable.Rows[i - 1]["Col3"] = txtHoraInicio.Text;
dtCurrentTable.Rows[i - 1]["Col4"] = txtHoraFin.Text;
dtCurrentTable.Rows[i - 1]["Col5"] = cboRepuesto.SelectedValue;
dtCurrentTable.Rows[i - 1]["Col6"] = txtCantidad.Text;
dtCurrentTable.Rows[i - 1]["Col7"] = txtDescripcion.Text;
rowIndex++;
}
ViewState["CurrentTable"] = dtCurrentTable;
}
SetPreviousData();
}
Use ClientIDMode="Predictable" instead of ClientIDMode="Static" inside the item-templates.

Getting exception while deleting rows from GridView

I want to delete selected rows from a GridView. For this I have written the below code, but I am getting an exception:
An unhandled exception of type 'System.StackOverflowException' occurred in System.Web.dll
Here is my aspx.page:
<asp:gridview ID="Gridview1" runat="server" ShowFooter="true"
onrowcommand="Gridview1_RowCommand" AutoGenerateColumns="false"
CellSpacing="0" CellPadding="0" Font-Bold="false"
onrowdeleting="Gridview1_RowDeleting">
<Columns>
<asp:TemplateField HeaderText="Select" ControlStyle-Width="50px" HeaderStyle-Font-Bold="false" ControlStyle-Font-Bold="false">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" Width="80px"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 1" HeaderStyle-Font-Bold="false" ControlStyle-Font-Bold="false">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Width="70px"></asp:TextBox>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotal" runat="server" Text="Total" Font-Bold="true"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 2" HeaderStyle-Font-Bold="false" ControlStyle-Font-Bold="false">
<ItemTemplate>
<asp:TextBox ID="TextBox2" Width="70px" runat="server" class="calculate" onchange="calculate()"></asp:TextBox>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="total" runat="server" Width="70px"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 3" HeaderStyle-Font-Bold="false" ControlStyle-Font-Bold="false">
<ItemTemplate>
<asp:TextBox ID="TextBox3" Width="70px" runat="server" ></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" CommandName="AddNewRow" />
<asp:Button ID="btnDelete" runat="server" CommandName="DeleteRow" Text="Delete"
OnClientClick="return DeleteConfirmation();"/>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:gridview>
Here is the code behind the aspx page:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SetInitialRow();
}
}
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++;
}
//add new row to DataTable
dtCurrentTable.Rows.Add(drCurrentRow);
//Store the current data to ViewState
ViewState["CurrentTable"] = dtCurrentTable;
//Rebind the Grid with the current data
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++;
}
}
}
}
protected void Gridview1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "AddNewRow")
{
AddNewRowToGrid();
}
if (e.CommandName == "DeleteRow")
{
for (int i = 0; i < Gridview1.Rows.Count; i++)
{
CheckBox chkDelete = (CheckBox)
Gridview1.Rows[i].Cells[0].FindControl("chkSelect");
if (chkDelete != null)
{
if (chkDelete.Checked)
{
//strID = GridView1.Rows[i].Cells[1].Text;
//idCollection.Add(strID);
Gridview1.DeleteRow(i);
}
}
}
}
Gridview1.DataBind();
}
protected void Gridview1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
for (int i = 0; i < Gridview1.Rows.Count; i++)
{
CheckBox chkDelete = (CheckBox)
Gridview1.Rows[i].Cells[0].FindControl("chkSelect");
if (chkDelete != null)
{
if (chkDelete.Checked)
{
//strID = GridView1.Rows[i].Cells[1].Text;
//idCollection.Add(strID);
Gridview1.DeleteRow(i);
}
}
}
Gridview1.DataBind();
}
}
I don't think you need to implement the RowDeleting event in your code. The RowDeleting event is just there to inform the program that a row is gonna get deleted.
In your example the RowDeleting event is calling the DeleteRow method, wich will cause RowDeleting event to be triggered and then the circle will just happend again. This circle will eventually end when the computer sees no other option then to cause a StackOverflowException and end your program.

Categories

Resources