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.
Related
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 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?
I have made a simple code to show you my problem.
I have a dynamic gridview with a variety of controls.
I want the 2nd dropdown list to get populated with specific data which depend on the selected index of the first drop down list.
So for instance let's say we have droplist1 with 4 options so droplist1.SelectedIndex is 1,2,3,4.
When i select (option)2 there's the event triggered on select and droplist2 goes droplist2.datasource = based on droplist1.SelectedIndex , ( i hope you understand).
I have managed to populate the droplist2 after the droplist1.SelectedIndex event BUT i can't get the value to be saved...
I saw on the debugger that it goes till one point but after that the line appears empty on my screen...
Here's my HTML
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication4.WebForm1" ClientIDMode="Static" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div style="height: 337px">
<asp:GridView ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false" OnSelectedIndexChanged="Gridview1_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Column1">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="Category" DataTextField="ExpenseCategoryName" DataValueField="ExpenseCategoryName" AppendDataBoundItems="true" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Value="-1">Select</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="Category" runat="server" ConnectionString="<%$ ConnectionStrings:Expenses_NewConnectionString %>" SelectCommand="SELECT [ExpenseCategoryName] FROM [ExpenseCategories]"></asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Column2">
<ItemTemplate>
<asp:DropDownList ID="DropDownList2" runat="server"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row"
OnClick="ButtonAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<br />
<br />
</div>
</form>
</body>
</html>
and my C# code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
setInitialRow();
}
}
protected void Gridview1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
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)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dt.Rows.Add(dr);
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++)
{
DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("DropDownList1");
DropDownList ddl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("DropDownList2");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Column1"] = ddl1.SelectedValue;
dtCurrentTable.Rows[i - 1]["Column2"] = ddl2.SelectedValue;
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++)
{
DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("DropDownList1");
DropDownList ddl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("DropDownList2");
try
{
ddl1.Text = dt.Rows[i]["Column1"].ToString();
ddl2.Text = dt.Rows[i]["Column2"].ToString();
}
catch (Exception ex)
{ }
rowIndex++;
}
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
DropDownList ddl1 = (DropDownList)Gridview1.Rows[(dt.Rows.Count - 1)].Cells[1].FindControl("DropDownList1");
DropDownList ddl2 = (DropDownList)Gridview1.Rows[(dt.Rows.Count - 1)].Cells[2].FindControl("DropDownList2");
FillDropDownList(ddl2);
}
}
}
private ArrayList GetData()
{
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 = GetData();
foreach (ListItem item in arr)
{
ddl.Items.Add(item);
}
}
}
}
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.
I have this code below. I am trying to add rows in gridview on demand and then bind the dropdownlist in the gridview and on adding a new row want to retain the values selected in the previous row. The problem is i am able to bind the dropdownlist and also do a cascading, but on ading a new row i am not able to retain the selection of the previous row. Please review the code and let me know where i am wrong.
<asp:GridView ID="gvAdvisor" runat="server" ShowFooter="true" AutoGenerateColumns="false" Width="895px" OnRowDataBound="gvAdvisor_RowDataBound">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Region">
<ItemTemplate>
<asp:DropDownList ID="ddRegion" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddRegion_SelectedIndexChanged">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Agency">
<ItemTemplate>
<asp:DropDownList ID="ddAgency" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddAgency_SelectedIndexChanged">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Firm">
<ItemTemplate>
<asp:DropDownList ID="ddFirm" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddFirm_SelectedIndexChanged">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Office">
<ItemTemplate>
<asp:DropDownList ID="ddOffice" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddOffice_SelectedIndexChanged">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Advisor">
<ItemTemplate>
<asp:DropDownList ID="ddAdvisor" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="%">
<ItemTemplate>
<asp:TextBox ID="txtPercent" runat="server" />
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="AddRowButton" runat="server" Text="Add New Row"
OnClick="ButtonAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SetInitialRow();
}
}
private void SetInitialRow()
{
try
{
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)));
dt.Columns.Add(new DataColumn("Column4", typeof(string)));
dt.Columns.Add(new DataColumn("Column5", typeof(string)));
dt.Columns.Add(new DataColumn("Column6", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dr["Column3"] = string.Empty;
dr["Column4"] = string.Empty;
dr["Column5"] = string.Empty;
dr["Column6"] = string.Empty;
dt.Rows.Add(dr);
//Store the DataTable in ViewState
ViewState["CurrentTable"] = dt;
gvAdvisor.DataSource = dt;
gvAdvisor.DataBind();
}
catch (Exception Ex)
{
//logger.Info("SetInitialRow : " + Ex.Message);
}
}
private void AddNewRowToGrid()
{
try
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
//extract the TextBox values
//if (tbBushels.Text != "" && tbLocation.Text != "" && tbFuture.Text != "" && tbBasis.Text != "" && tbPrice.Text != "" && tbRevenue.Text != "")
//{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
DropDownList Region =
(DropDownList)gvAdvisor.Rows[rowIndex].Cells[1].FindControl("ddRegion");
DropDownList Agency =
(DropDownList)gvAdvisor.Rows[rowIndex].Cells[2].FindControl("ddAgency");
DropDownList Firm =
(DropDownList)gvAdvisor.Rows[rowIndex].Cells[3].FindControl("ddFirm");
DropDownList Office =
(DropDownList)gvAdvisor.Rows[rowIndex].Cells[4].FindControl("ddOffice");
DropDownList Advisor =
(DropDownList)gvAdvisor.Rows[rowIndex].Cells[5].FindControl("ddAdvisor");
TextBox Percent =
(TextBox)gvAdvisor.Rows[rowIndex].Cells[6].FindControl("txtPercent");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
drCurrentRow["Column1"] = Region.SelectedItem.Value;
drCurrentRow["Column2"] = Agency.SelectedItem.Value;
drCurrentRow["Column3"] = Firm.SelectedItem.Value;
drCurrentRow["Column4"] = Office.SelectedItem.Value;
drCurrentRow["Column5"] = Advisor.SelectedItem.Value;
drCurrentRow["Column6"] = Percent.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
gvAdvisor.DataSource = dtCurrentTable;
gvAdvisor.DataBind();
//}
}
}
else
{
Response.Write("ViewState is null");
}
//Set Previous Data on Postbacks
SetPreviousData();
}
catch (Exception Ex)
{
//logger.Info("AddNewRowToGrid : " + Ex.Message);
}
}
private void SetPreviousData()
{
try
{
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++)
{
DropDownList Region =
(DropDownList)gvAdvisor.Rows[rowIndex].Cells[1].FindControl("ddRegion");
Region.SelectedItem.Value = dt.Rows[i]["Column1"].ToString();
foreach (GridViewRow gvr in gvAdvisor.Rows)
{
if (gvr.RowType == DataControlRowType.DataRow)
{
// DropDownList ddRegion = (DropDownList)gvr.FindControl("ddRegion");
DropDownList ddAgency = (DropDownList)gvr.FindControl("ddAgency");
if (Region.SelectedItem.Value == "0")
{
}
else
{
ddHelp.BindAgencyByRegion(ddAgency, Convert.ToInt32(Region.SelectedItem.Value));
}
ListItem ll1 = new ListItem("Select", "0");
ddAgency.Items.Insert(0, ll1);
}
}
DropDownList Agency =
(DropDownList)gvAdvisor.Rows[rowIndex].Cells[2].FindControl("ddAgency");
Agency.SelectedItem.Value = dt.Rows[i]["Column2"].ToString();
foreach (GridViewRow gvr in gvAdvisor.Rows)
{
if (gvr.RowType == DataControlRowType.DataRow)
{
//DropDownList ddAgency = (DropDownList)gvr.FindControl("ddAgency");
DropDownList ddFirm = (DropDownList)gvr.FindControl("ddFirm");
if (Agency.SelectedItem.Value == "0")
{
}
else
{
ddHelp.BindFirm(ddFirm, Convert.ToInt32(Agency.SelectedItem.Value));
}
ListItem ll2 = new ListItem("Select", "0");
ddFirm.Items.Insert(0, ll2);
}
}
DropDownList Firm =
(DropDownList)gvAdvisor.Rows[rowIndex].Cells[3].FindControl("ddFirm");
Firm.SelectedItem.Value = dt.Rows[i]["Column3"].ToString();
foreach (GridViewRow gvr in gvAdvisor.Rows)
{
if (gvr.RowType == DataControlRowType.DataRow)
{
//DropDownList ddFirm = (DropDownList)gvr.FindControl("ddFirm");
DropDownList ddOffice = (DropDownList)gvr.FindControl("ddOffice");
if (Firm.SelectedItem.Value == "0")
{
}
else
{
ddHelp.BindOffice(ddOffice, 0, Convert.ToInt32(Firm.SelectedItem.Value), 0);
}
ListItem ll3 = new ListItem("Select", "0");
ddOffice.Items.Insert(0, ll3);
}
}
DropDownList Office =
(DropDownList)gvAdvisor.Rows[rowIndex].Cells[4].FindControl("ddOffice");
Office.SelectedItem.Value = dt.Rows[i]["Column4"].ToString();
foreach (GridViewRow gvr in gvAdvisor.Rows)
{
if (gvr.RowType == DataControlRowType.DataRow)
{
//DropDownList ddOffice = (DropDownList)gvr.FindControl("ddOffice");
DropDownList ddAdvisor = (DropDownList)gvr.FindControl("ddAdvisor");
if (Office.SelectedItem.Value == "0")
{
}
else
{
ddHelp.BindAdvisor(ddAdvisor, 0, 0, Convert.ToInt32(Office.SelectedItem.Value));
}
ListItem ll4 = new ListItem("Select", "0");
ddAdvisor.Items.Insert(0, ll4);
}
}
DropDownList Advisor =
(DropDownList)gvAdvisor.Rows[rowIndex].Cells[5].FindControl("ddAdvisor");
TextBox Percent =
(TextBox)gvAdvisor.Rows[rowIndex].Cells[6].FindControl("txtPercent");
Advisor.SelectedItem.Value = dt.Rows[i]["Column5"].ToString();
Percent.Text = dt.Rows[i]["Column6"].ToString();
rowIndex++;
}
}
}
}
catch (Exception Ex)
{
//logger.Info("SetPreviousData : " + Ex.Message);
}
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
protected void gvAdvisor_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (ViewState["CurrentTable"] != null)
{
Datatable dt = (Datatable)ViewState["CurrentTable"];
if (e.Row.RowType == DataControlRowType.DataRow)
{
((DropDownList)gvAdvisor.Rows[rowIndex].FindControl("ddRegion")).SelectedValue = dt[rowindex]["Column1"];
((DropDownList)gvAdvisor.Rows[rowIndex].FindControl("ddRegion")).Items.Insert(0,new ListItem("Select", "0"));
}
}
else
{
SetInitialRow();
}
}
In gvAdvisor_RowDataBound event
Assign the data from viewstate[currenttable] to a datatable
foreach datarow have a loop using the row index
assign the value from the datatable to dropdownlist using the row index and the column name
sample : (Dropdownlist)(gvAdvisor.Rows[i].findcontrol("ddRegion")).SelectedValue = datatable[i]["Region"];
You need to tweak the above code to suit best for your grid view
You can use the similar logic for other controls as well Checkbox, radiobuttons etc