i want multiple rows default in a gridview..
but i have a code like,
<asp:gridview ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Header 1">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 2">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 3">
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
after click "Add New Row" button in .cs file ,
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
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();
}
http://www.aspsnippets.com/Articles/Adding-Dynamic-Rows-in-ASP.Net-GridView-Control-with-TextBoxes.aspx
here only 1 row is there default, but i need atleast 4 rows,
then how to save that in db too.
help...
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.
Hi I'm having a great issue because I don't know where to start. I need to create a Gridview which has to buttons below it, a "Create Row" button and a "Delete Row" button. I want that everytime the "Create Row" button is pressed a new row to be added to the GridView, however the main problem is that I need that new row to be filled with different controls such as DropDownLists and TextBox, but I have no idea of how to do it properly. Here is an image of how I want the GridView to be:
Each row has 2 dropdown lists, two textbox and a button
I know that I need to bind the GridView to a data source such as a dataTable, but I have no idea if that will work with controls such as TextBox or DropDownLists. Sorry if I don't add any code because I really don't know where to start. Thank you.
If i understood it right u can follow this:
Create Gridview
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound"
OnRowCommand="GridView1_RowCommand" DataKeyNames="RowNumber">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" Visible="false" />
<asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Middle">
<ItemTemplate>
<asp:CheckBox runat="server" ID="chkSelect"
ToolTip="Select To Delete This Row" />
<asp:Label runat="server" ID="lblId" Text='<%# Bind("Id") %>'
Visible="false"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Entry">
<ItemTemplate>
<asp:Label runat="server" ID="lblFirstEntry" Visible="false" Text='<%# Eval("FirstEntry") %>'></asp:Label>
<asp:DropDownList ID="ddlFirstEntry" runat="server" ClientIDMode="Static" CssClass="ddlFirstEntry">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Second Entry">
<ItemTemplate>
<asp:Label runat="server" ID="lblSecondEntry" Visible="false" Text='<%# Eval("SecondEntry") %>'></asp:Label>
<asp:DropDownList ID="ddlSecondEntry" runat="server" ClientIDMode="Static" CssClass="ddlSecondEntry">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Text Box">
<ItemTemplate>
<asp:Label runat="server" ID="lblFirstTextBox" Visible="false"></asp:Label>
<asp:TextBox ID="txtFirstTextBox" runat="server" Text='<%# Eval("FirstTextBox") %>'
CssClass="txtFirstTextBox"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Second Text Box">
<ItemTemplate>
<asp:Label runat="server" ID="lblSecondTextBox" Visible="false"></asp:Label>
<asp:TextBox ID="txtFSecondTextBox" runat="server" Text='<%# Eval("SecondTextBox") %>'
CssClass="txtSecondTextBox"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Second Text Box">
<ItemTemplate>
<asp:Button ID="btnSubmit" runat="server" Text="Button" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Then in Code behind in Page_Load call this method
private void InitializeGrid()
{
try
{
ViewState["applicationDetail"] = null;
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[]
{
new DataColumn("Id", typeof(int)),
new DataColumn("FirstEntry", typeof(string)),
new DataColumn("SecondEntry",typeof(string)),
new DataColumn("FirstTextBox", typeof(string)),
new DataColumn("SecondTextBox", typeof(string))
});
DataRow drRow = dt.NewRow();
drRow["Id"] = 1;
drRow["FirstEntry"] = string.Empty;
drRow["SecondEntry"] = string.Empty;
drRow["FirstTextBox"] = string.Empty;
drRow["SecondTextBox"] = string.Empty;
dt.Rows.Add(drRow);
ViewState["applicationDetail"] = dt;
GridView1.DataSource = ViewState["applicationDetail"];
}
catch (Exception ex)
{
throw;
}
}
InitializeGrid();
GridView1.DataBind();
On GridView1_RowDataBound Bind All your drop down controls
upto this will create a grid with one empty row.
Now On Add Button Click do following
protected void btnNewRow_Click(object sender, EventArgs e)
{
try
{
AddNewRowToGrid();
}
catch (Exception ex)
{
throw ex;
}
}
private void AddNewRowToGrid()
{
try
{
int rowIndex = 0;
if (ViewState["applicationDetail"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["applicationDetail"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the TextBox values _lblGuestId
DropDownList ddl1 = GridView1.Rows[rowIndex].FindControl("ddlFirstEntry") as DropDownList;
DropDownList ddl2 = GridView1.Rows[rowIndex].FindControl("ddlSecondEntry") as DropDownList;
TextBox txt1 = GridView1.Rows[rowIndex].FindControl("txtFirstTextBox") as TextBox;
TextBox txt2 = GridView1.Rows[rowIndex].FindControl("txtSecondTextBox") as TextBox;
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["FirstEntry"] = ddl1.SelectedValue;
dtCurrentTable.Rows[i - 1]["SecondEntry"] = ddl2.SelectedValue;
dtCurrentTable.Rows[i - 1]["FirstTextBox"] = txt1.Text;
dtCurrentTable.Rows[i - 1]["SecondTextBox"] = txt2.Text;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["applicationDetail"] = dtCurrentTable;
GridView1.DataSource = dtCurrentTable;
GridView1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
//Set Previous Data on Postbacks
SetPreviousData();
}
catch (Exception ex)
{
throw ex;
}
}
private void SetPreviousData()
{
try
{
int rowIndex = 0;
if (ViewState["applicationDetail"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["applicationDetail"];
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 0; i < dtCurrentTable.Rows.Count; i++)
{
DropDownList ddl1 = GridView1.Rows[rowIndex].FindControl("ddlFirstEntry") as DropDownList;
DropDownList ddl2 = GridView1.Rows[rowIndex].FindControl("ddlSecondEntry") as DropDownList;
TextBox txt1 = GridView1.Rows[rowIndex].FindControl("txtFirstTextBox") as TextBox;
TextBox txt2 = GridView1.Rows[rowIndex].FindControl("txtSecondTextBox") as TextBox;
ddl1.SelectedValue = dtCurrentTable.Rows[i]["FirstEntry"].ToString();
ddl2.SelectedValue = dtCurrentTable.Rows[i]["SecondEntry"].ToString();
txt1.Text = dtCurrentTable.Rows[i]["FirstTextBox"].ToString();
txt2.Text = dtCurrentTable.Rows[i]["SecondTextBox"].ToString();
rowIndex++;
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
For Deleting
On GridView1_RowCommand when check box is checked get row indexes of all the checked check box rows and keep it in some session or application variable.
On delete button click use that variable for deleting the rows.
I hope your problem will be solved.
As per your comment i am adding GridView1_RowDataBound for drop down bindings
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
DropDownList ddl1 = (e.Row.FindControl("ddlFirstEntry") as DropDownList);
Label lbl1 = (e.Row.FindControl("lblFirstEntry") as Label);
DropDownList ddl2 = (e.Row.FindControl("ddlSecondEntry") as DropDownList);
Label lbl2 = (e.Row.FindControl("lblSecondEntry") as Label);
ddl1.Items.Clear();
ddl1.AppendDataBoundItems = true;
ddl1.Items.Add(new ListItem("-Select-", "-1"));
ddl1.DataSource = ViewState["ddl1datasourse"];
ddl1.DataTextField = "Value";
ddl1.DataValueField = "Id";
ddl1.DataBind();
if (ddl1.SelectedValue != string.Empty && lbl1.Text != null)
ddl1.SelectedValue = lbl1.Text.Trim();
else
ddl1.SelectedValue = "-1";
ddl2.Items.Clear();
ddl2.AppendDataBoundItems = true;
ddl2.Items.Add(new ListItem("-Select-", "-1"));
ddl2.DataSource = ViewState["ddl2datasourse"];
ddl2.DataTextField = "Value";
ddl2.DataValueField = "Id";
ddl2.DataBind();
if (ddl2.SelectedValue != string.Empty && lbl2.Text != null)
ddl2.SelectedValue = lbl2.Text.Trim();
else
ddl2.SelectedValue = "-1";
}
catch (Exception ex)
{
throw ex;
}
}
I am trying to import data from a csv to a gridview, but for some reason, I get the following error:
DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'Col5'.
Here is how the csv looks like:
I would like to display in the GridView in this same format, and set the column names and row names to "Q1, "Q2", "Q3", "Q4", "Q5".
Could anyone please help? Thank you in advance. P.S: I am a beginner at ASP.NET
Here is my code:
aspx
<asp:GridView ID="TurnoverGridView" runat="server" ShowHeaderWhenEmpty="True" AutoGenerateColumns="False"
Width="318px" CellPadding="4" ForeColor="#333333" GridLines="None" AllowSorting="True">
<AlternatingRowStyle BackColor="White" Height="2px" />
<Columns>
<asp:TemplateField HeaderText="">
<ItemStyle Font-Size="13px" Width="10%" />
<ItemTemplate>
<asp:Label ID="RowLabel" runat="server" ReadOnly="true" Text='<%# Eval("Col1") %>'
Style="text-align: left; font-weight:bold"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Q1">
<ItemStyle Font-Size="13px" Width="16%" />
<ItemTemplate>
<asp:Label ID="FirstLabel" runat="server" ReadOnly="true" Text='<%# Eval("Col2") %>'
Style="text-align: left;"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Q2">
<ItemStyle Font-Size="13px" Width="16%" />
<ItemTemplate>
<asp:Label ID="SecondLabel" runat="server" ReadOnly="true" Text='<%# Eval("Col3") %>'
Style="text-align: left;"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Q3">
<ItemStyle Font-Size="13px" Width="16%" />
<ItemTemplate>
<asp:Label ID="ThirdLabel" runat="server" ReadOnly="true" Text='<%# Eval("Col4") %>'
Style="text-align: left;"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Q4">
<ItemStyle Font-Size="13px" Width="16%" />
<ItemTemplate>
<asp:Label ID="FourthLabel" runat="server" ReadOnly="true" Text='<%# Eval("Col5") %>'
Style="text-align: left;"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Q5">
<ItemStyle Font-Size="13px" Width="16%" />
<ItemTemplate>
<asp:Label ID="FifthLabel" runat="server" ReadOnly="true" Text='<%# Eval("Col6") %>'
Style="text-align: left;"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#EBEBEB" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" Height="10px" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string dir = #"Directory"; // Directory where the file exists
string turnover_fi = dir + "\\turnover_ac_bull.csv";
FirstTurnoverGridViewRow();
DataTable dt = (DataTable)Session["currentTurnoverTable"];
//DataTable dt = new DataTable();
dt = (DataTable)ReadToEnd(turnover_fi);
if (dt != null && dt.Rows.Count > 0)
{
TurnoverGridView.DataSource = dt;
TurnoverGridView.DataBind();
}
}
}
private object ReadToEnd(string filePath)
{
DataTable dtDataSource = new DataTable();
string[] fileContent = File.ReadAllLines(filePath);
if (fileContent.Count() > 0)
{
string[] columns = fileContent[0].Split(',');
for (int i = 0; i < columns.Count() - 1; i++)
{
dtDataSource.Columns.Add("Col" + (i + 1));
}
for (int i = 0; i < fileContent.Count(); i++)
{
string[] row = fileContent[i].Split(',').Take(fileContent[i].Split(',').Length - 1).ToArray();
DataRow dr = dtDataSource.NewRow();
for (int j = 0; j < row.Length; j++)
{
dr[j] = row[j];
}
dtDataSource.Rows.Add(dr);
}
}
return dtDataSource;
}
protected void FirstTurnoverGridViewRow()
{
DataTable table = new DataTable();
string[] row_names = new string[] { "Q1", "Q2", "Q3", "Q4", "Q5" };
table.Columns.Add(new DataColumn("Col1", typeof(string)));
table.Columns.Add(new DataColumn("Col2", typeof(double)));
table.Columns.Add(new DataColumn("Col3", typeof(double)));
table.Columns.Add(new DataColumn("Col4", typeof(double)));
table.Columns.Add(new DataColumn("Col5", typeof(double)));
table.Columns.Add(new DataColumn("Col6", typeof(double)));
DataRow dr = table.NewRow();
for (int i = 0; i < row_names.Count(); i++)
{
dr = table.NewRow();
string text = row_names[i];
dr["Col1"] = row_names[i];
dr["Col2"] = DBNull.Value;
dr["Col3"] = DBNull.Value;
dr["Col4"] = DBNull.Value;
dr["Col5"] = DBNull.Value;
dr["Col6"] = DBNull.Value;
table.Rows.Add(dr);
}
ViewState["currentTurnoverTable"] = table;
TurnoverGridView.Visible = true;
TurnoverGridView.DataSource = table;
TurnoverGridView.DataBind();
}
the for loop inside ReadToEnd(string filePath) function
for (int i = 0; i < columns.Count() - 1; i++)
{
dtDataSource.Columns.Add("Col" + (i + 1));
}
it should read as
for (int i = 0; i < columns.Count(); i++)
{
dtDataSource.Columns.Add("Col" + (i + 1));
}
I have a GridView that is bound to a DataTable, and when you select edit, I can get the values to change. However, one field needs to be a dropdownlist and not a textbox. Here's the code I have so far.
protected void griditems_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
DataTable dt = (DataTable)Session["table"];
//Update the values.
GridViewRow row = griditems.Rows[e.RowIndex];
dt.Rows[row.DataItemIndex]["Part"] = ((TextBox)(row.Cells[1].Controls[0])).Text.ToUpper();
dt.Rows[row.DataItemIndex]["Quantity"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Ship-To"] = ((TextBox)(row.Cells[3].Controls[0])).Text.ToUpper();
dt.Rows[row.DataItemIndex]["Requested Date"] = ((TextBox)(row.Cells[4].Controls[0])).Text;
//dt.Rows[row.DataItemIndex]["Shipping Method"] = ((TextBox)(row.Cells[5].Controls[0])).Text;
DropDownList cmbType = (DropDownList)griditems.Rows[e.RowIndex].FindControl("Shipping Method");
griditems.EditIndex = -1;
BindData();
}
}
When I uncomment the line for the shipping method to be a textbox, it does just as it says, a textbox, not a dropdownlist. I have tried changing it to a DropDownList with no luck.
In the aspx file:
<asp:GridView ID="griditems" runat="server"
onrowdeleting="griditems_RowDeleting" onrowediting="griditems_RowEditing"
onrowupdating="griditems_RowUpdating" AllowPaging="True" onpageindexchanging="griditems_PageIndexChanging"
onrowcancelingedit="griditems_RowCancelingEdit" ViewStateMode="Enabled" Caption="Order Details"
AutoGenerateDeleteButton="True" AutoGenerateEditButton="True"
onrowdatabound="griditems_RowDataBound" >
<EditRowStyle BackColor="#FF9900" BorderStyle="Double" /></asp:GridView>
and when the table is generated:
public void CreateTable()
{
DataTable table = new DataTable();
if (Session["table"] != null)
table = (DataTable)Session["table"];
else
{
table.Columns.Add("Part", typeof(string));
table.Columns.Add("Quantity", typeof(Int32));
table.Columns.Add("Ship-To", typeof(string));
table.Columns.Add("Requested Date", typeof(string));
table.Columns.Add("Shipping Method", typeof(string));
}
DataRow row = table.NewRow();
row["Part"] = part;
row["Quantity"] = qty;
row["Ship-To"] = shipto;
row["Requested Date"] = reqdate;
row["Shipping Method"] = shipmthd;
table.Rows.Add(row);
Session["table"] = table;
griditems.DataSource = table.DefaultView;
griditems.DataBind();
}
Try dis:
Default.aspx: (Best practise use Template Field in GridView)
<asp:GridView ID="gvshipping" runat="server" AutoGenerateColumns="False"
onrowcancelingedit="gvshipping_RowCancelingEdit"
onrowdatabound="gvshipping_RowDataBound"
onrowediting="gvshipping_RowEditing" CellPadding="4" ForeColor="#333333"
GridLines="None">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Part">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("part") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" Text='<%# Bind("part") %>' runat="server"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quatity">
<ItemTemplate>
<asp:Label ID="lblqty" runat="server" Text='<%# Bind("quantity") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtqty" runat="server" Text='<%# Bind("quantity") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Ship to">
<ItemTemplate>
<asp:Label ID="lblshipto" runat="server" Text='<%# Bind("ShipTo") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtshipto" runat="server" Text='<%# Bind("ShipTo") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Post date">
<ItemTemplate>
<asp:Label ID="lblpostdate" runat="server" Text='<%# Bind("RequestedDate")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtpostdate" Text='<%# Bind("RequestedDate")%>' runat="server"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Shipping Method">
<ItemTemplate>
<asp:Label ID="lblshipmethod" runat="server" Text='<%# Bind("ShippingMethod")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True"
CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"
CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#7C6F57" />
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#E3EAEB" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F8FAFA" />
<SortedAscendingHeaderStyle BackColor="#246B61" />
<SortedDescendingCellStyle BackColor="#D4DFE1" />
<SortedDescendingHeaderStyle BackColor="#15524A" />
</asp:GridView>
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
gvBind();
}
}
public void gvBind()
{
DataTable dt = createTable();
Session["tb"] = dt;
gvshipping.DataSource = Session["tb"];
gvshipping.DataBind();
}
protected void gvshipping_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList dpshipmethod = (DropDownList)e.Row.FindControl("DropDownList1");
//bind dropdownlist
DataTable dt = shipingmethodTable();
dpshipmethod.DataSource = dt;
dpshipmethod.DataTextField = "ShippingMethod";
dpshipmethod.DataValueField = "Id";
dpshipmethod.DataBind();
DataRowView dr = e.Row.DataItem as DataRowView;
dpshipmethod.SelectedItem.Text = dr["ShippingMethod"].ToString();
}
}
}
protected void gvshipping_RowEditing(object sender, GridViewEditEventArgs e)
{
gvshipping.EditIndex = e.NewEditIndex;
vBind();
}
protected void gvshipping_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvshipping.EditIndex = -1;
gvBind();
}
public DataTable createTable()
{
DataTable dt = new DataTable();
dt.Columns.Add("Part", typeof(string));
dt.Columns.Add("Quantity", typeof(Int32));
dt.Columns.Add("ShipTo", typeof(string));
dt.Columns.Add("RequestedDate", typeof(string));
dt.Columns.Add("ShippingMethod", typeof(string));
string date= DateTime.Now.ToShortDateString();
DataRow row = dt.NewRow();
row["Part"] = "Anchor";
row["Quantity"] = "10";
row["ShipTo"] = "blah";
row["RequestedDate"] = date;
row["ShippingMethod"] = "Charge by subtotal";
dt.Rows.Add(row);
DataRow row1 = dt.NewRow();
row1["Part"] = "blade";
row1["Quantity"] = "88";
row1["ShipTo"] = "blah";
row1["RequestedDate"] = date;
row1["ShippingMethod"] = "Charge by quantity";
dt.Rows.Add(row1);
DataRow row2 = dt.NewRow();
row2["Part"] = "cabin";
row2["Quantity"] = "4";
row2["ShipTo"] = "blah";
row2["RequestedDate"] = date;
row2["ShippingMethod"] = "Charge by subtotal";
dt.Rows.Add(row2);
DataRow row3 = dt.NewRow();
row3["Part"] = "cockpit";
row3["Quantity"] = "11";
row3["ShipTo"] = "blah";
row3["RequestedDate"] = date;
row3["ShippingMethod"] = "Charge by weight";
dt.Rows.Add(row3);
DataRow row4 = dt.NewRow();
row4["Part"] = "jack";
row4["Quantity"] = "45";
row4["ShipTo"] = "blah";
row4["RequestedDate"] = date;
row4["ShippingMethod"] = "Charge by weight";
dt.Rows.Add(row4);
DataRow row5 = dt.NewRow();
row5["Part"] = "cabin";
row5["Quantity"] = "67";
row5["ShipTo"] = "blah";
row5["RequestedDate"] = date;
row5["ShippingMethod"] = "Charge by weight";
dt.Rows.Add(row5);
DataRow row6 = dt.NewRow();
row6["Part"] = "blade";
row6["Quantity"] = "4";
row6["ShipTo"] = "blah";
row6["RequestedDate"] = date;
row6["ShippingMethod"] = "Charge by weight";
dt.Rows.Add(row6);
return dt;
}
public DataTable shipingmethodTable()
{
DataTable dtshipingmethod = new DataTable();
dtshipingmethod.Columns.Add("Id", typeof(Int32));
dtshipingmethod.Columns.Add("ShippingMethod", typeof(string));
DataRow row = dtshipingmethod.NewRow();
row["Id"] = 1;
row["ShippingMethod"] = "Charge by subtotal";
dtshipingmethod.Rows.Add(row);
DataRow row1 = dtshipingmethod.NewRow();
row1["Id"] = 2;
row1["ShippingMethod"] = "Charge by weight";
dtshipingmethod.Rows.Add(row1);
DataRow row2 = dtshipingmethod.NewRow();
row2["Id"] = 3;
row2["ShippingMethod"] = "Charge by quantity";
dtshipingmethod.Rows.Add(row2);
return dtshipingmethod;
}
ScreenShot:
you can go ahead with the help of this:
dt.Rows[row.DataItemIndex]["Shipping Method"] = ((DropDownList)row.FindControl("DropdownList1")).SelectedItem;
EDIT:
dt.Rows[row.DataItemIndex]["Shipping Method"] = ((DropDownList)
(row.Cells[5].Controls[0])).SelectedItem.ToString();
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.