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
Related
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.
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.
The code shown here is adding a blank row and inserting the row into database, but not displaying it at run time. Please can someone edit that code and help me to get what I am expecting. Please help me. I am fed up of doing. I am not getting it. If someone has a code what I am expecting please send me to my mail id : sivaraman.loganathan#gmail.com
<body>
<form id="form1" runat="server">
<div>
<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" Text='<%# Eval("Column1") %>'></asp:TextBox>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 2">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Eval("Column2") %>'></asp:TextBox>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 3">
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Eval("Column3") %>'></asp:TextBox>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:gridview>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row"
OnClick="ButtonAdd_Click" />
<asp:Button ID="Button1" runat="server" Text="Button"
OnClick="ButtonSave_Click"/>
</div>
</form>
</body>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SetInitialRow();
}
}
private void BindData()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(GetConnectionString()))
{
string strQuery = "SELECT * FROM SampleTabL";
SqlCommand cmd = new SqlCommand(strQuery);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
}
}
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();
}
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();
}
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++;
}
}
}
}
private string GetConnectionString()
{
//"DBConnection" is the name of the Connection String
//that was set up from the web.config file
return System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
}
private void InsertRecords(StringCollection sc)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
StringBuilder sb = new StringBuilder(string.Empty);
string[] splitItems = null;
foreach (string item in sc)
{
const string sqlStatement = "INSERT INTO SampleTabl (Column1,Column2,Column3) VALUES";
if (item.Contains(","))
{
splitItems = item.Split(",".ToCharArray());
sb.AppendFormat("{0}('{1}','{2}','{3}'); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2]);
}
}
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sb.ToString(), conn);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
//Display a popup which indicates that the record was successfully inserted
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
protected void ButtonSave_Click(object sender, EventArgs e)
{
int rowIndex = 0;
StringCollection sc = new StringCollection();
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the TextBox values
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
//get the values from the TextBoxes
//then add it to the collections with a comma "," as the delimited values
sc.Add(box1.Text + "," + box2.Text + "," + box3.Text);
rowIndex++;
}
//Call the method for executing inserts
InsertRecords(sc);
}
}
}
The question wasn't that clear so I am assuming that you want to store the data inserted in gridview and want it to be displayed on same gridview after pageload.
If that is the case then the problem with your code is that you are not calling a BindData() method on pageload. Another one is calling SetInitialRow() on pageload might mess with the gridview in which you are trying to bind data.
You can do the following:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
private void BindData()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(GetConnectionString()))
{
string strQuery = "SELECT * FROM SampleTabL";
SqlCommand cmd = new SqlCommand(strQuery);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
if (dt.Rows.Count>0)
{
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
else
{
SetInitialRow();
}
}
}
}
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.