C# - Transfer value from one page to a dynamic gridview's textbox - c#

Here is my aspx page, describing a dynamic gridview:
<asp:gridview ID="Gridview1" runat="server" ShowFooter="True"
AutoGenerateColumns="False"
OnRowCreated="Gridview1_RowCreated" style="margin-left: 13px; margin-right: 6px; margin-top: 12px;" Width="1035px" CellPadding="4" ForeColor="Black" GridLines="Horizontal" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="#" />
<asp:TemplateField HeaderText="Disease">
<ItemTemplate>
<asp:Button ID="Icd" runat="server" Text="ICD 10" Height="23px" Width="69px" OnClick="Icd_Click" />
<asp:TextBox ID="TextBox1" runat="server" Height="23px" Width="301px" MaxLength="100"></asp:TextBox>
</ItemTemplate>
<ItemStyle CssClass="gvCell"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Year">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Height="23px" Width="95px" MaxLength="4"></asp:TextBox>
</ItemTemplate>
<ItemStyle CssClass="gvCell"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Stuation">
<ItemStyle CssClass="gvCell"></ItemStyle>
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"
AppendDataBoundItems="true" Height="23px">
<asp:ListItem Value="-1">--Επιλέξτε--</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Therapy">
<ItemStyle CssClass="gvCell"></ItemStyle>
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Height="23px" Width="223px" MaxLength="100"></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>
<ItemStyle CssClass="gvCell"></ItemStyle>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server"
onclick="LinkButton1_Click">Delete row</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#006466" ForeColor="Black" />
<HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#4B4B4B" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#242121" />
And here is the aspx.cs code:
private ArrayList GetDummyData()
{
ArrayList arr = new ArrayList();
arr.Add(new ListItem("Πάσχει", "1"));
arr.Add(new ListItem("Έπασχε", "2"));
return arr;
}
private void FillDropDownList(DropDownList ddl)
{
ArrayList arr = GetDummyData();
foreach (ListItem item in arr)
{
ddl.Items.Add(item);
}
}
private void SetInitialRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dt.Columns.Add(new DataColumn("Column1", typeof(string)));//for TextBox value
dt.Columns.Add(new DataColumn("Column2", typeof(string)));//for TextBox value
dt.Columns.Add(new DataColumn("Column3", typeof(string)));//for DropDownList selected item
dt.Columns.Add(new DataColumn("Column4", typeof(string)));//for TextBox value
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = 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[3].FindControl("DropDownList1");
FillDropDownList(ddl1);
}
private void AddNewRowToGrid()
{
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = dtCurrentTable.Rows.Count + 1;
//add new row to DataTable
dtCurrentTable.Rows.Add(drCurrentRow);
//Store the current data to ViewState for future reference
ViewState["CurrentTable"] = dtCurrentTable;
for (int i = 0; i < dtCurrentTable.Rows.Count - 1; i++)
{
//extract the TextBox values
TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)Gridview1.Rows[i].Cells[3].FindControl("TextBox3");
dtCurrentTable.Rows[i]["Column1"] = box1.Text;
dtCurrentTable.Rows[i]["Column2"] = box2.Text;
dtCurrentTable.Rows[i]["Column4"] = box3.Text;
//extract the DropDownList Selected Items
DropDownList ddl1 = (DropDownList)Gridview1.Rows[i].Cells[3].FindControl("DropDownList1");
// Update the DataRow with the DDL Selected Items
dtCurrentTable.Rows[i]["Column3"] = ddl1.SelectedItem.Text;
}
//Rebind the Grid with the current data to reflect changes
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
//Set Previous Data on Postbacks
SetPreviousData();
}
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("TextBox2");
DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[3].FindControl("DropDownList1");
TextBox box3 = (TextBox)Gridview1.Rows[i].Cells[4].FindControl("TextBox3");
//Fill the DropDownList with Data
FillDropDownList(ddl1);
if (i < dt.Rows.Count - 1)
{
//Assign the value from DataTable to the TextBox
box1.Text = dt.Rows[i]["Column1"].ToString();
box2.Text = dt.Rows[i]["Column2"].ToString();
//Set the Previous Selected Items on Each DropDownList on Postbacks
ddl1.ClearSelection();
ddl1.Items.FindByText(dt.Rows[i]["Column3"].ToString()).Selected = true;
box3.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 string GetConnectionString()
{
return ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString;
}
private void InsertRecords(StringCollection sc)
{
if (Session["pa_id"] != null)
{
StringBuilder sb = new StringBuilder(string.Empty);
string[] splitItems = null;
const string sqlStatement = "INSERT INTO P_deasease (Date,P_Id,Nosos,Situ,Year_d,Therapy) VALUES";
int id = Convert.ToInt32(Session["pa_id"]);
foreach (string item in sc)
{
if (item.Contains(","))
{
splitItems = item.Split(",".ToCharArray());
sb.AppendFormat("{0}(#Date, #p_id ,N'{1}',N'{2}',N'{3}',N'{4}'); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2], splitItems[3]);
}
}
using (SqlConnection connection = new SqlConnection(GetConnectionString()))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand(sb.ToString(), connection))
{
cmd.Parameters.AddWithValue("#p_id", id);
cmd.Parameters.AddWithValue("#Date", DateTime.Now.ToShortDateString());
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "Success!";
}
else
{
lblid1.Visible = true;
}
}
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 values
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[3].FindControl("DropDownList1");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("TextBox3");
//add them to the collections with a comma "," as the delimited values
sc.Add(string.Format("{0},{1},{2},{3}", box1.Text, ddl1.SelectedItem.Text, box2.Text, box3.Text));
rowIndex++;
}
//Call the method for executing inserts
InsertRecords(sc);
}
}
}
As you can see in the 1st column there is a button along with a textbox.
When you click the button, a popup window appears in which there is something like "search-in-the-database" mechanism.
So, when a value is selected in the popup window's gridview, I want to transfer it to the corresponding text box.
How do I transfer the value into the corresponding textbox? As a beginner, I am dealing a great difficulty into that part. Any help will be appreciated

Related

ASP.NET dropdownlist in GridView keeps clearing up

I have 2 dropdownlists in grid view. The selection of the first one (EqpCatDDL) will determine what values the second one (DescripDDL) will be populated with.
However, everytime I click the Add New Row button, the DescripDDL dropdownlist clears up. I don't know why it does that. The following is the code:
aspx:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:GridView ID="Gridview1" runat="server" ShowFooter="True" AutoGenerateColumns="False"
OnRowDataBound="Gridview1_RowDataBound">
<Columns>
<asp:BoundField DataField="S/N" HeaderText="S/N" />
<asp:TemplateField HeaderText="Item Name">
<ItemTemplate>
<asp:DropDownList ID="EqpCatDDL" runat="server" AutoPostBack="true" OnSelectedIndexChanged="EqpCatDDL_SelectedIndexChanged">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:DropDownList ID="DescripDDL" runat="server" AutoPostBack="true">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Remarks">
<ItemTemplate>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<contenttemplate>
<asp:Button ID="ButtonAdd" onclick="ButtonAdd_Click" runat="server" Text="Add New Row" />
</contenttemplate>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
c#:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SetInitialRow(); //create a datatable to bind to GridView
}
}
private void SetInitialRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("S/N", 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)));
dr = dt.NewRow();
dr["S/N"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dr["Column3"] = string.Empty;
dr["Column4"] = string.Empty;
dt.Rows.Add(dr);
//Store the DataTable in ViewState
ViewState["CurrentTable"] = dt;
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
GridViewRow row = (GridViewRow)((sender as Button).NamingContainer);
Button btn = row.FindControl("ButtonAdd") as Button;
ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(btn);
}
private void AddNewRowToGrid()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
//extract the TextBox values
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//Locate controls in GridView
DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("EqpCatDDL");
DropDownList ddl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("DescripDDL");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
TextBox box4 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("TextBox4");
//Save control values into DataTable
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["S/N"] = i + 1;
drCurrentRow["Column1"] = ddl1.SelectedValue.ToString();
drCurrentRow["Column2"] = ddl2.SelectedValue.ToString();
drCurrentRow["Column3"] = box3.Text;
drCurrentRow["Column4"] = box4.Text;
dtCurrentTable.Rows[rowIndex]["Column1"] = ddl1.SelectedValue.ToString();
dtCurrentTable.Rows[rowIndex]["Column2"] = ddl2.SelectedValue.ToString();
dtCurrentTable.Rows[rowIndex]["Column3"] = box3.Text;
dtCurrentTable.Rows[rowIndex]["Column4"] = box4.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");
}
SetPreviousData(); //Set Previous Data from DataTable to GridView on Postbacks from Add New Row button click
}
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-1); i++)
{
DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("EqpCatDDL");
DropDownList ddl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("DescripDDL");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
TextBox box4 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("TextBox4");
ddl1.Text = dt.Rows[i]["Column1"].ToString();
ddl2.Text = dt.Rows[i]["Column2"].ToString();
box3.Text = dt.Rows[i]["Column3"].ToString();
box4.Text = dt.Rows[i]["Column4"].ToString();
rowIndex++;
}
}
}
}
//Populate Item Name dropdownlist from EqpCat column in EqpCategory table
protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string connString = ConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString;
SqlConnection connection = new SqlConnection(connString);
//Find the DropDownList in the Row
DropDownList EqpCatDDL = (e.Row.FindControl("EqpCatDDL") as DropDownList);
SqlCommand cmd1 = new SqlCommand("SELECT DISTINCT EqpCat FROM EqpCategory", connection);
cmd1.Connection.Open();
SqlDataReader ddlValues1;
ddlValues1 = cmd1.ExecuteReader();
EqpCatDDL.DataSource = ddlValues1;
EqpCatDDL.DataTextField = "EqpCat";
EqpCatDDL.DataValueField = "EqpCat";
EqpCatDDL.DataBind();
cmd1.Connection.Close();
cmd1.Connection.Dispose();
//Add Default Item in the DropDownList
EqpCatDDL.Items.Insert(0, new ListItem("--Select--"));
}
}
//Populate Description dropdownlist based on selected value of Item Name dropdownlist
protected void EqpCatDDL_SelectedIndexChanged(object sender, EventArgs e)
{
string connString = ConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString;
SqlConnection connection = new SqlConnection(connString);
GridViewRow gvr = (GridViewRow)((DropDownList)sender).Parent.Parent;
DropDownList EqpCatDDL = gvr.FindControl("EqpCatDDL") as DropDownList;
DropDownList DescripDDL = gvr.FindControl("DescripDDL") as DropDownList;
string cate = EqpCatDDL.SelectedValue.ToString();
SqlCommand cmd2 = new SqlCommand("SELECT Description FROM EqpCategory WHERE EqpCat = '" + cate + "'", connection);
cmd2.Connection.Open();
SqlDataReader ddlValues2;
ddlValues2 = cmd2.ExecuteReader();
DescripDDL.DataSource = ddlValues2;
DescripDDL.DataTextField = "Description";
DescripDDL.DataValueField = "Description";
DescripDDL.DataBind();
cmd2.Connection.Close();
cmd2.Connection.Dispose();
//Add Default Item in the DropDownList
DescripDDL.Items.Insert(0, new ListItem("--Select--"));
}
I am currently using: Visual Studio 2010 with SSMS 2008
Just modify your SetPreviousData Function
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 - 1); i++)
{
DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("EqpCatDDL");
DropDownList ddl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("DescripDDL");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
TextBox box4 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("TextBox4");
ddl1.SelectedValue = dt.Rows[i]["Column1"].ToString();
string connString = ConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString;
SqlConnection connection = new SqlConnection(connString);
SqlCommand cmd2 = new SqlCommand(""SELECT Description FROM EqpCategory WHERE EqpCat = '" + Convert.ToInt32(ddl1.SelectedValue) + "'", connection);
cmd2.Connection.Open();
SqlDataReader ddlValues2;
ddlValues2 = cmd2.ExecuteReader();
ddl2.DataTextField = "Description";
ddl2.DataValueField = "Description";
ddl2.DataSource = ddlValues2;
ddl2.DataBind();
cmd2.Connection.Close();
cmd2.Connection.Dispose();
ddl2.SelectedValue = dt.Rows[i]["Column2"].ToString();
box3.Text = dt.Rows[i]["Column3"].ToString();
box4.Text = dt.Rows[i]["Column4"].ToString();
rowIndex++;
}
}
}
}
Use SelectedValue (https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.selectedvalue(v=vs.110).aspx) instead of text to set the selected item.
E.g.:
ddl1.SelectedValue = dt.Rows[i]["Column1"].ToString();
ddl2.SelectedValue = dt.Rows[i]["Column2"].ToString();

Add new row in gridview while button onclick

This is my program that page load the gridview and retrieve the database record to textbox and i put a add new button wish to add new row exactly like that row but the textbox is empty.
I wanted to create a new row in GridView while click add new button while my TextBox is retrieve data from database. I try to run the code but it is nothing happen when i click the button. Hope someone may help. Thanks.
My front end code
<Columns>
<asp:TemplateField HeaderStyle-CssClass="display_none">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Font-Bold="true" Font-Size="Medium">Name</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-CssClass="display_none">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" CssClass="NormalInputTextField" Text='<%#Eval("SLMN") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-CssClass="display_none">
<ItemTemplate>
<asp:Button ID="BtnDelete" runat="server" Text="Delete" CssClass="btn btn-primary" CommandName="remove" CommandArgument='<%# Container.DataItemIndex %>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField FooterStyle-BorderStyle="None" HeaderStyle-CssClass="display_none">
<ItemTemplate>
<asp:Button ID="BtnSearch2" runat="server" Text="Search" CssClass="btn btn-primary" CommandName="ViewComments" OnClientClick="javascript:saveData(this,'grid')"/>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" BorderStyle="None"/>
<FooterTemplate>
<asp:Button ID="BtnAdd" runat="server" Text="Add New Row" CssClass="btn btn-primary" OnClick="ButtonAdd_Click"/>
</FooterTemplate>
</asp:TemplateField>
</Columns>
My back end code
private void AddNewRowToGrid()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
dt.Columns.Add(new DataColumn("Column2", typeof(string)));
dr = dt.NewRow();
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dt.Rows.Add(dr);
}
My onclick event to call add new function
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
My gridview tag
<grd:MultiSelectGridView ID="grid2" runat="server" Width="500px"
CssClass="paging_gridview" AllowPaging="True"
AutoGenerateColumns ="false" PageSize="10" PagerType="Custom"
ShowFooter="true" OnRowDeleting="grid2_RowDeleting"
MultiSelectDataKeyName="Urid,Name" ShowHeaderWhenEmpty="true"
MultiSelectColumnIndex="0" EnableMultiSelect="false" GridLines="None" BorderStyle="None" OnRowCommand="grid2_RowCommand"
>
i bind my record to gridview by page load
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Loadgrid();
}
}
private void Loadgrid()
{
string branch = txtBranch.Text.Trim();
string name = txtName.Text.Trim();
string sql = "SELECT * FROM fcs_cotmdl WHERE TMDL= '" + name + "'AND CONO='" + branch + "' ";
SqlDataSource2.ConnectionString = ConfigurationManager.ConnectionStrings["ConnStr_epsi"].ConnectionString;
SqlDataSource2.ConnectionString = SqlDataSource2.ConnectionString.Replace("Provider=OraOLEDB.Oracle.1;", "");
SqlDataSource con = new SqlDataSource();
SqlDataSource2.SelectCommand = sql;
grid2.DataSourceID = "SqlDataSource2";
grid2.DataBind();
}
Following tutorial details the exact same scenario. Please refer to it.
Adding Dynamic Rows to Gridview on Button Click
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");
//Instead of all the textboxes, use the button as you require.
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();
}
And then the SetPreviousData() Function:
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++;
}
}
}
}
Then inside your Click Event:
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
From your Load grid method you should retrieve the data as a data table and bind to grid. And save in in session. Like this:
private void Loadgrid()
{
var dt = new DataTable();
using (var conn = new SqlConnection (ConfigurationManager.ConnectionStrings["ConnectionStringName"].ToString()))
{
var command = new SqlCommand();
command.Connection = conn;
command.CommandText = "SELECT * FROM [dbo].[T1]";
command.CommandType = CommandType.Text;
using (var adaptor = new SqlDataAdapter(command))
{
if (conn.State == ConnectionState.Closed) conn.Open();
adaptor.Fill(dt);
if (conn.State == ConnectionState.Open) conn.Close();
}
}
Session["ss"] = dt;
grid2.DataSource = dt;
grid2.DataBind();
}
private void AddNewRowToGrid()
{
DataTable dt = (DataTable) Session["ss"];
DataRow dr = null;
DataRow newBlankRow1 = dt.NewRow();
dt.Rows.Add(newBlankRow1);
grid2.DataSource = dt;
grid2.DataBind();
Session["ss"] = dt;
}
After add an empty row also you need to bind data to grid again.

How to show unique key exception before saving into database?

I've created a gridview in which user can enter items and their quantities. The number of items are unknown so the requirement was that to able to add as much items the users want to. So I've given a provision to add item row for another entry. All these data entered gets into a temporary table and one all done by click on a button all these datas will save onto database.
Is there any way to hide the items which has been already selected on the previous row or show an error that the item has been already enter while selecting the dropdown value, before clicking on the button.
My gridview looks something like this:
gridview code:
<asp:GridView ID="gvItemList" runat="server" AutoGenerateColumns="False" AutoGenerateDeleteButton="True" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2" CssClass="newStyle9" ForeColor="Black" OnRowDataBound="gvItemList_RowDataBound" OnRowDeleting="gvItemList_RowDeleting" ShowFooter="True" style="text-align: center" ViewStateMode="Enabled">
<Columns>
<asp:TemplateField HeaderText="Sl No" SortExpression="Id">
<ItemTemplate>
<asp:Label ID="lblId" runat="server" Text="<%# Container.DataItemIndex+1 %>"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item Description">
<ItemTemplate>
<asp:DropDownList ID="ddlItem" runat="server" Height="25px" Width="200px" AutoPostBack="True" OnSelectedIndexChanged="ddlItem_SelectedIndexChanged">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Unit">
<ItemTemplate>
<asp:Label ID="txtUnit" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="txtQty" runat="server" Height="27px" Width="73px"></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="AddRowButton" runat="server" OnClick="ButtonAdd_Click" Text="Add New Item" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
<RowStyle BackColor="White" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
Code behind:
private void SetInitialRowToGrid()
{
// Initialize and Set initial row of Datatable
var tempDataTable = new DataTable();
tempDataTable.Columns.Add("lblId");
tempDataTable.Columns.Add("ddlItem");
tempDataTable.Columns.Add("txtUnit");
tempDataTable.Columns.Add("txtQty");
tempDataTable.Rows.Add("1", "", "", "");
// Store that datatable into viewstate
ViewState["TempTable"] = tempDataTable;
// Attach Gridview Datasource to datatable
gvItemList.DataSource = tempDataTable;
gvItemList.DataBind();
}
private void AddNewRowToGrid()
{
int rowIndex = 0;
if (ViewState["TempTable"] != null)
{
// Get TempTable from viewstate
var tempTable = (DataTable)ViewState["TempTable"];
DataRow tempRow = null;
if (tempTable.Rows.Count > 0)
{
for (int i = 1; i <= tempTable.Rows.Count; i++)
{
// Get Grid's values
var Item =
(DropDownList)gvItemList.Rows[rowIndex].Cells[2].FindControl("ddlItem");
var Unit =
(Label)gvItemList.Rows[rowIndex].Cells[3].FindControl("txtUnit");
var Qty =
(TextBox)gvItemList.Rows[rowIndex].Cells[4].FindControl("txtQty");
// Create new row and update Row Number
tempRow = tempTable.NewRow();
tempTable.Rows[i - 1]["ddlItem"] = Item.SelectedValue;
tempTable.Rows[i - 1]["txtUnit"] = Unit.Text;
tempTable.Rows[i - 1]["txtQty"] = Qty.Text;
rowIndex++;
}
// Add data to datatable and viewstate
tempTable.Rows.Add(tempRow);
ViewState["TempTable"] = tempTable;
// Attach Gridview Datasource to datatable
gvItemList.DataSource = tempTable;
gvItemList.DataBind();
}
}
//Set Previous Data on Postbacks
SetPreviousData();
}
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["TempTable"] != null)
{
var tempTable = (DataTable)ViewState["TempTable"];
if (tempTable.Rows.Count > 0)
{
for (int i = 0; i < tempTable.Rows.Count; i++)
{
var Item =
(DropDownList)gvItemList.Rows[rowIndex].Cells[2].FindControl("ddlItem");
var Unit =
(Label)gvItemList.Rows[rowIndex].Cells[3].FindControl("txtUnit");
var Qty =
(TextBox)gvItemList.Rows[rowIndex].Cells[4].FindControl("txtQty");
Item.SelectedValue = tempTable.Rows[i]["ddlItem"].ToString();
Unit.Text = tempTable.Rows[i]["txtUnit"].ToString();
Qty.Text = tempTable.Rows[i]["txtQty"].ToString();
rowIndex++;
}
}
}
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
protected void gvItemList_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int index = Convert.ToInt32(e.RowIndex);
deleteRow(index);
SetPreviousData();
if (gvItemList.Rows.Count == 0)
{
SetInitialRowToGrid();
}
}
private int deleteRow(int index)
{
int rowIndex = 0;
if (ViewState["TempTable"] != null)
{
// Get TempTable from viewstate
var tempTable = (DataTable)ViewState["TempTable"];
if (tempTable.Rows.Count > 0)
{
for (int i = 1; i <= tempTable.Rows.Count; i++)
{
// Get Grid's TextBox values
var Item =
(DropDownList)gvItemList.Rows[rowIndex].Cells[2].FindControl("ddlItem");
var Unit =
(Label)gvItemList.Rows[rowIndex].Cells[3].FindControl("txtUnit");
var Qty =
(TextBox)gvItemList.Rows[rowIndex].Cells[4].FindControl("txtQty");
}
// Add data to datatable and viewstate
tempTable.Rows.RemoveAt(index);
ViewState["TempTable"] = tempTable;
// Attach Gridview Datasource to datatable
gvItemList.DataSource = tempTable;
gvItemList.DataBind();
}
}
//Set Previous Data on Postbacks
return index;
}
protected void gvItemList_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlItem = (e.Row.FindControl("ddlItem") as DropDownList);
Jilu1TableAdapters.tbl_ItemTableAdapter item;
item = new Jilu1TableAdapters.tbl_ItemTableAdapter();
DataTable dt = new DataTable();
dt = item.GetItems();
ddlItem.DataSource = dt;
ddlItem.DataTextField = "Item";
ddlItem.DataValueField = "Item";
ddlItem.DataBind();
ddlItem.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--Select an Item--", "0"));
}
}
private void InsertRecords(StringCollection sc)
{
Jilu1TableAdapters.tbl_Jr_BOMTableAdapter ds;
ds = new Jilu1TableAdapters.tbl_Jr_BOMTableAdapter();
StringBuilder sb = new StringBuilder(string.Empty);
string[] splitItems = null;
string user = Page.User.Identity.Name;
try
{
foreach (string item in sc)
{
if (item.Contains(",,,"))
{
//To prevent null reference error
}
else
{
splitItems = item.Split(",".ToCharArray());
ds.InsertJrBOM(ddlState.SelectedValue, ddlDistrict.SelectedValue, ddlCluster.SelectedValue, ddlSiteID.SelectedValue, txtSiteName.Text, ddlSiteType.SelectedValue, txtNoBTS.Text, txtNoLinks.Text, txtLoadBand.Text, ddlEBAvailability.SelectedValue, txtEBPhase.Text, txtDGCapacity.Text, txtDGPhase.Text, splitItems[0], splitItems[1], splitItems[2], user, DateTime.Now, "Nil", 1, txtDispatch.Text);
}
}
lblSuccess.Visible = true;
lblSuccess.Text = "Records Successfully Saved!";
Timer1.Enabled = true;
}
catch (System.Data.SqlClient.SqlException)
{
lblErrorMessage.Visible = true;
lblErrorMessage.Text = "Duplicate Items has been entered, please correct it before proceeding or an entry for " + ddlSiteID.Text + " has already made, please go to edit page to make necessary changes!";
Timer1.Enabled = true;
return;
}
catch (Exception ex)
{
lblErrorMessage.Visible = true;
lblErrorMessage.Text = "Error: " + ex.Message;
Timer1.Enabled = true;
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
int rowIndex = 0;
StringCollection sc = new StringCollection();
if (ViewState["TempTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["TempTable"];
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the TextBox values
DropDownList ddlItem = (DropDownList)gvItemList.Rows[rowIndex].Cells[2].FindControl("ddlItem");
Label txtUnit = (Label)gvItemList.Rows[rowIndex].Cells[3].FindControl("txtUnit");
TextBox txtQty = (TextBox)gvItemList.Rows[rowIndex].Cells[4].FindControl("txtQty");
//get the values from the TextBoxes
//then add it to the collections with a comma "," as the delimited values
sc.Add(ddlItem.SelectedValue + "," + txtUnit.Text + "," + txtQty.Text);
if (sc.Contains(",,,"))
{
lblErrorMessage.Visible = true;
lblErrorMessage.Text = "Fields should not be left empty!";
Timer1.Enabled = true;
return;
}
else
{
string Quantity = txtQty.Text;
float num;
if (float.TryParse(Quantity, out num))
{
rowIndex++;
}
else
{
lblErrorMessage.Visible = true;
lblErrorMessage.Text = "Quantity field must be a number!";
Timer1.Enabled = true;
return;
}
}
}
//Call the method for executing inserts
InsertRecords(sc);
if (lblSuccess.Text == "Records Successfully Saved!")
{
this.SetInitialRowToGrid();
string user = Page.User.Identity.Name;
StatusTableAdapters.tbl_NotificationsTableAdapter ds2;
ds2 = new StatusTableAdapters.tbl_NotificationsTableAdapter();
ds2.InsertNotification(ddlSiteID.SelectedValue, "BOM Notification", DateTime.Now, user, "Role6");
}
}
}
}
Any help will be greatly appreciated.
protected void ddlItem_SelectedIndexChanged(object sender, EventArgs e)
{
var main = (sender as DropDownList);
foreach (GridViewRow row in gvItemList.Rows)
{
var ddl = (row.FindControl("ddlItem") as DropDownList);
if (main.ClientID != ddl.ClientID && ddl.SelectedValue == main.SelectedValue)
{
row.BackColor = System.Drawing.Color.Red;
string script = "alert('already selected!');";
ScriptManager.RegisterStartupScript(this, GetType(),
"ServerControlScript", script, true);
}
}
}

Preserve textbox values inside a gridview on button click

I have an editable GridView, which has a AddRow button, on click of which an empty row consisting of text boxes is added.
Whenever I insert values inside these textboxes, and click AddRow or Delete button, the text boxes loose their values.
I am sure, this doesn't happen due to postback, because there's a Save button too, on the click of which the values are normally preserved.
Below is the markup:
<asp:GridView ID="GridView1" runat="server" ShowFooter="true" AutoGenerateColumns="false"
OnRowDeleting="GridView1_RowDeleting">
<Columns>
<asp:TemplateField HeaderText="Col1">
<ItemTemplate>
<asp:TextBox runat="server" ID="txt1"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Col2">
<ItemTemplate>
<asp:TextBox ID="txt2" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Col3">
<ItemTemplate>
<asp:TextBox ID="txt3" runat="server"></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="btnAddNewRow" runat="server" Text="AddRow" OnClick="Add" />
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Button" ShowDeleteButton="true" />
</Columns>
</asp:GridView>
<asp:Button ID="btnSavetoDB" runat="server" Text="save" OnClick="btnSavetoDB_Click" />
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SetInitialRow();
}
}
//Sets the first empty row to the grid view
private void SetInitialRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
dt.Columns.Add(new DataColumn("Column2", typeof(string)));
dt.Columns.Add(new DataColumn("Column3", typeof(string)));
dr = dt.NewRow();
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();
}
//Adds a new empty row to the grid view
protected void Add(object sender, EventArgs e)
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 0; i < dtCurrentTable.Rows.Count; i++)
{
//extract the TextBox values
TextBox box1 = (TextBox)GridView1.Rows[rowIndex].Cells[0].FindControl("txt1");
TextBox box2 = (TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txt2");
TextBox box3 = (TextBox)GridView1.Rows[rowIndex].Cells[2].FindControl("txt3");
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");
}
}
//Called on Delete Button click, which is inside a CommanField
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int num = GridView1.Rows.Count;
int index = Convert.ToInt32(e.RowIndex);
if (num > 1)
{
DataTable dt = ViewState["CurrentTable"] as DataTable;
dt.Rows[index].Delete();
ViewState["CurrentTable"] = dt;
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
Initial snapshot:
After AddRow button click:
Where am I going wrong?
Experts please help.
Regards
The problem is that you haven't used Eval in your markup
<asp:TextBox runat="server" ID="txt1" Text='<%# Eval("Column1") %>'></asp:TextBox>
Optimized code-behind. No need of ViewState
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var table = CreateDataTable();
table.Rows.Add("", "", "");
BindGridView(table);
}
}
//Sets the first empty row to the grid view
private DataTable CreateDataTable()
{
var dt = new DataTable
{
Columns = { "Column1", "Column2", "Column3" }
};
return dt;
}
private void BindGridView(DataTable table)
{
GridView1.DataSource = table;
GridView1.DataBind();
}
private DataTable PopulateTableFromGridView()
{
var table = CreateDataTable();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
//extract the TextBox values
TextBox box1 = (TextBox)GridView1.Rows[i].FindControl("txt1");
TextBox box2 = (TextBox)GridView1.Rows[i].FindControl("txt2");
TextBox box3 = (TextBox)GridView1.Rows[i].FindControl("txt3");
table.Rows.Add(box1.Text, box2.Text, box3.Text);
}
return table;
}
//Adds a new empty row to the grid view
protected void Add(object sender, EventArgs e)
{
var newTable = PopulateTableFromGridView();
newTable.Rows.Add("", "", "");
BindGridView(newTable);
}
//Called on Delete Button click, which is inside a CommanField
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
var dt = PopulateTableFromGridView();
dt.Rows[e.RowIndex].Delete();
if (dt.Rows.Count == 0)
{
dt.Rows.Add("", "", "");
}
BindGridView(dt);
}
Links on inline expressions
http://support.microsoft.com/kb/976112
http://weblogs.asp.net/ahmedmoosa/embedded-code-and-inline-server-tags

Access the textbox value from gridview

I have a dynamic gridview ...and it has four columns..what I want is to access the textbox value in the gridview from the last column "amount paid" and display its total sum value in a label.Below is the code that I have tried. can someone let me know how to do this?
ASP.NET
<asp:gridview ID="Gridview2" runat="server" ShowFooter="true" CssClass="vutblrow"
TabIndex="3" HeaderStyle-CssClass="vutblhdr"
CellPadding="4" ForeColor="#333333" GridLines="None" Width="1%"
PagerStyle-Mode="NumericPages"
AutoGenerateColumns="false" onrowcreated="Gridview2_RowCreated" Height="16px">
<PagerStyle CssClass="pgr" Height="25px" BorderStyle="Solid" />
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Serial Number" />
<asp:TemplateField HeaderText="From Place">
<ItemTemplate>
<asp:TextBox ID="Textfrom" runat="server" CssClass="txtBoxNormalmedium"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="To Place">
<ItemTemplate>
<asp:TextBox ID="Textto" runat="server" CssClass="txtBoxNormalmedium"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Distance Travelled (kms)">
<ItemTemplate>
<asp:TextBox ID="TextBoxdist" runat="server" CssClass="txtBoxNormalmedium"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Amount Paid (per km)">
<ItemTemplate>
<asp:TextBox ID="TextBoxamt" runat="server" CssClass="txtBoxNormalmedium"></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd1" runat="server" Text="Add New Row"
CssClass="btnNormalAdd" OnClick="add" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton2" runat="server"
CssClass="lnkbut" OnClick="LinkButton2_Click">Remove</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:gridview>
<asp:Label ID="lblTotal" runat="server" Text="Label"></asp:Label>
C# code:
namespace Test.Test
{
public partial class WebForm6 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SetInitialRow1();
}
}
private void AddNewRowToGrid1()
{
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)Gridview2.Rows[rowIndex].Cells[1].FindControl("Textfrom");
TextBox box2 = (TextBox)Gridview2.Rows[rowIndex].Cells[2].FindControl("Textto");
TextBox box3 = (TextBox)Gridview2.Rows[rowIndex].Cells[3].FindControl("TextBoxdist");
TextBox box4 = (TextBox)Gridview2.Rows[rowIndex].Cells[3].FindControl("TextBoxamt");
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;
dtCurrentTable.Rows[i - 1]["Column4"] = box4.Text;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
Gridview2.DataSource = dtCurrentTable;
Gridview2.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
//Set Previous Data on Postbacks
SetPreviousData1();
}
private void SetPreviousData1()
{
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)Gridview2.Rows[rowIndex].Cells[1].FindControl("Textfrom");
TextBox box2 = (TextBox)Gridview2.Rows[rowIndex].Cells[2].FindControl("Textto");
TextBox box3 = (TextBox)Gridview2.Rows[rowIndex].Cells[3].FindControl("TextBoxdist");
TextBox box4 = (TextBox)Gridview2.Rows[rowIndex].Cells[3].FindControl("TextBoxamt");
box1.Text = dt.Rows[i]["Column1"].ToString();
box2.Text = dt.Rows[i]["Column2"].ToString();
box3.Text = dt.Rows[i]["Column3"].ToString();
box4.Text = dt.Rows[i]["Column4"].ToString();
rowIndex++;
}
}
}
}
protected void add(object sender, EventArgs e)
{
AddNewRowToGrid1();
}
protected void Gridview2_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 LinkButton2_Click(object sender, EventArgs e)
{
LinkButton lb = (LinkButton)sender;
GridViewRow gvRow = (GridViewRow)lb.NamingContainer;
int rowID = gvRow.RowIndex + 1;
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
dt.Rows.Remove(dt.Rows[rowID]);
}
}
//Store the current data in ViewState for future reference
ViewState["CurrentTable"] = dt;
//Re bind the GridView for the updated data
Gridview2.DataSource = dt;
Gridview2.DataBind();
}
//Set Previous Data on Postbacks
SetPreviousData1();
}
private void SetInitialRow1()
{
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)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dr["Column3"] = string.Empty;
dr["Column4"] = string.Empty;
dt.Rows.Add(dr);
//dr = dt.NewRow();
//Store the DataTable in ViewState
ViewState["CurrentTable"] = dt;
Gridview2.DataSource = dt;
Gridview2.DataBind();
}
}
}
GridViewRow row = (GridViewRow)((Button)sender).NamingContainer;
TextBox TextBox1 = row.FindControl("TextBox1") as TextBox;
//Access TextBox1 here.
string myString = TextBox1.Text;
Text box is the child control inside in gridview row so you can iterate above code for each grid view row.
Could you please isolate the data source?
This will clarify your mind and the question. As soon you have a Service/Repository to query the data source you can take advantage of linq and do something simple like:
var sum = datasource.Sum(p=>p.AmountPaid);

Categories