I have found a dynamic gridview code that creates lines and saves the one you filled last.
In my code i want to parse the droplist selected value text instead of actually writing in the textbox.
I have managed to parse the selectedvalue text in a textbox and for one line everything goes fine, but when i try to create a second line the selected value becomes the same for both lines.
(example: lets say i have a ddl menu with the values "a,b" if i choose the a value first the textbox will be filled ok "a" value, but if i choose b for the second line it will be both "b".
I will be needing 9 textboxes but i have made a simple version of the code containing only 1 textbox for the sake of space.
HTML
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication4.WebForm1" %>
<!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="Header 1">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</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 />
<asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<br />
<br />
<br />
</div>
</form>
</body>
</html>
C# code
namespace WebApplication4
{
public partial class WebForm1 : System.Web.UI.Page
{
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)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = 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++)
{
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
else
{
Response.Write("Viewstate is null");
}
SetPreviousData();
}
}
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
box1.Text = dt.Rows[i]["Column1"].ToString();
rowIndex++;
}
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
So as you'd imagine i tried going
box1.Text = DropDownList1.SelectedValue.ToString();
I tried with view state, but generally i failed.
Thanks for any of the answers guys!
ASPX Page
<asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
Code Behind
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
SetPreviousData();
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
TextBox box1 = (TextBox)Gridview1.Rows[(dt.Rows.Count - 1)].Cells[1].FindControl("TextBox1");
box1.Text = DropDownList1.SelectedValue;
}
}
}
Another Approach you can try is you can directly place dropdownlist in gridview instead of textbox.
Related
Good Day everyone,
I have a web application that is a basic input form. The input form has a dynamic gridview that allows users to enter any number of rows to enter trip information.
Most everything is working well except two aspects;
I have continued errors that say gridviewName is not in the current context
Finally the more important issue lies in the fact that my gridview does not appear in debug in the browser (regardless of the browser chosen).
I have researched this for a week now and I think I need a new set of eyes on this. What could I be missing in my codebehind and aspx pages to make my gridview show up and the CodeBehind page to recognize the designer file.
<%# Page Language="C#" AutoEventWireup="True" MasterPageFile="~/Site.Master" CodeBehind="intakeTripDetails.aspx.cs" Inherits="WebApplication2.TravelerInformation" %>
<asp:Content ID="intakeTripDets" ContentPlaceHolderID="MainContent" runat="server">
<fieldset>
<legend>Trip Details</legend>
<div class="input">
<p>Please enter trip details on the below form. You can add additional rows as needed for each leg of our trip.</p>
<br />
<asp:Label runat="server" ID="lblMessage" Text="" ></asp:Label><br />
<label>Flight Number(s)</label><asp:TextBox runat="server"></asp:TextBox>
<br /><br /><br /><br />
<asp:GridView ID="tripDetails" runat="server" ShowFooter="True" ShowHeaderWhenEmpty="True">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="" />
<asp:TemplateField HeaderText="Arrival Date & Time" >
<ItemTemplate>
<asp:TextBox ID="arrivalDateTime" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Departure Date & Time">
<ItemTemplate>
<asp:TextBox ID="departDateTime" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Country">
<ItemTemplate>
<asp:DropDownList ID="countryList" runat="server" AutoPostBack="true" AppendDataBoundItems="true">
<asp:ListItem Value="-1">--SELECT--</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<ItemTemplate>
<asp:TextBox ID="city" runat="server">
</asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="btnAdd" runat="server" Text="Add New Row" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkRemove" runat="server">Remove</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<div class="btnfmt"><%--<asp:Button ID="prev" runat="server" Text="Previous: Traveler Information" />--%>
<asp:Button ID="submit" runat="server" text="Submit Trip"/> </div>
</div>
</fieldset> </asp:Content>
CodeBehind:
using System;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace travelDetails
{
public partial class DynamicGrid : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SetInitialRow();
}
}
private ArrayList countryData()
{
ArrayList arr = new ArrayList();
arr.Add(new ListItem("Afghanistan", "1"));
arr.Add(new ListItem("Aland Islands", "2"));
arr.Add(new ListItem("Albania", "3"));
arr.Add(new ListItem("Algeria", "4"));
arr.Add(new ListItem("American Samoa", "5"));
arr.Add(new ListItem("Andorra", "6"));
arr.Add(new ListItem("Angola", "7"));
arr.Add(new ListItem("Anguilla", "8"));
arr.Add(new ListItem("Antarctica", "9"));
arr.Add(new ListItem("Antigua and Barbuda", "10"));
arr.Add(new ListItem("Argentina", "11"));
arr.Add(new ListItem("Armenia", "12"));
arr.Add(new ListItem("Aruba", "13"));
arr.Add(new ListItem("Australia", "14"));
arr.Add(new ListItem("Austria", "15"));
arr.Add(new ListItem("Azerbaijan", "16"));
arr.Add(new ListItem("Bahamas", "17"));
arr.Add(new ListItem("Bahrain", "18"));
arr.Add(new ListItem("Bangladesh", "19"));
arr.Add(new ListItem("Barbados", "20"));
return arr;
}
private void FillDropDownList(DropDownList ddl)
{
ArrayList arr = countryData();
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("arrivalDateTime", typeof(DateTime)));
dt.Columns.Add(new DataColumn("departDateTime", typeof(DateTime)));
dt.Columns.Add(new DataColumn("city", typeof(string)));
dt.Columns.Add(new DataColumn("countryList", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["arrivalDateTime"] = string.Empty;
dr["departDateTime"] = string.Empty;
dr["city"] = string.Empty;
dt.Rows.Add(dr);
//What if I want to see the data for future reference
ViewState["CurrentTable"] = dt;
//Data is stuck here
tripDetails.DataSource = dt;
tripDetails.DataBind();
DropDownList ddl1 = (DropDownList)tripDetails.Rows[0].Cells[4].FindControl("countryList");
FillDropDownList(ddl1);
}
private void AddNewRowToGrid()
{
int rowIndex = 0;
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;
for (int i = 0; i < dtCurrentTable.Rows.Count - 1; i++)
{
//extract the textbox values
TextBox box1 = (TextBox)tripDetails.Rows[i].Cells[1].FindControl("arrivalDateTime");
TextBox box2 = (TextBox)tripDetails.Rows[i].Cells[2].FindControl("departDateTime");
TextBox box3 = (TextBox)tripDetails.Rows[i].Cells[3].FindControl("city");
dtCurrentTable.Rows[i]["arrivalDateTime"] = box1.Text;
dtCurrentTable.Rows[i]["departDateTime"] = box2.Text;
dtCurrentTable.Rows[i]["city"] = box3.Text;
//extract the ddl values
DropDownList ddl1 = (DropDownList)tripDetails.Rows[i].Cells[4].FindControl("countryList");
//Update the DataRow with the ddl items selected
dtCurrentTable.Rows[i]["countryList"] = ddl1.SelectedItem.Text;
}
//Adds new row to the data table
dtCurrentTable.Rows.Add(drCurrentRow);
//Again...we probably want to refer to this again
ViewState["CurrentTable"] = dtCurrentTable;
//Rebind the grid with the current data
tripDetails.DataSource = dtCurrentTable;
tripDetails.DataBind();
}
else
{
Response.Write("View State 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)tripDetails.Rows[i].Cells[2].FindControl("arrivalDateTime");
TextBox box2 = (TextBox)tripDetails.Rows[i].Cells[3].FindControl("departDateTime");
TextBox box3 = (TextBox)tripDetails.Rows[i].Cells[4].FindControl("city");
DropDownList ddl1 = (DropDownList)tripDetails.Rows[rowIndex].Cells[4].FindControl("countryList");
//Fill the ddl with data
FillDropDownList(ddl1);
if (i < dt.Rows.Count - 1)
{
//Assign the value from the datatable to the textbox
box1.Text = dt.Rows[i]["arrivalDateTime"].ToString();
box2.Text = dt.Rows[i]["departDateTime"].ToString();
box3.Text = dt.Rows[i]["city"].ToString();
//Set the previously selected items to each ddl
ddl1.ClearSelection();
ddl1.Items.FindByText(dt.Rows[i]["countryList"].ToString()).Selected = true;
}
rowIndex++;
}
}
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
protected void tripDetails_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
LinkButton lb = (LinkButton)e.Row.FindControl("lnkRemove");
if (lb != null)
{
if (dt.Rows.Count > 1)
{
if (e.Row.RowIndex == dt.Rows.Count - 1)
{
lb.Visible = true;
}
}
else
{
lb.Visible = true;
}
}
}
}
protected void lnkRemove_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 selected row data and reset row number
dt.Rows.Remove(dt.Rows[rowID]);
ResetRowID(dt);
}
}
//And another future reference
ViewState["CurrentTable"] = dt;
//Bind the data to the gridview again with updated data
tripDetails.DataSource = dt;
tripDetails.DataBind();
}
//Set previous data on postback
SetPreviousData();
}
private void ResetRowID(DataTable dt)
{
int rowNumber = 1;
if (dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
row[0] = rowNumber;
rowNumber++;
}
}
}
I have tried everything that I can think of -
1. Deleting Designer file and 'Converting to Web Application'
2. Redoing the code in another file
3. Recreating the whole project
4. Making everything visible/invisible
Any help would be great!
Edit:
Okay update, I have made some changes and now I have errors that indicate The type or namespace name 'DataBind' does not exist in the namespace 'tripDetails' (are you missing an assembly reference?). This error shows for 'DataBind' 'DataSource' and 'Rows.
What am I missing in my references or namespaces that could be causing these errors. I did not make any changes to this area.
Update I was able to finally clear all the errors but I still cannot see my empty gridview in the browsers. Anyone?
I think you have confused ID and Name. Name allows data to be assigned or retrieved from a control.
Change ID="tripDetails" to name="tripDetails" and it should work. Similarly, i'd then advise doing the same for the rest of the controls.
Hi I have a grid view with two columns text box and drop down list when I add values and click "ADD" button I want to add new row with Previous values,
I do it but my previous values refresh. Please help me.
This is my aspx
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvStudent" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:TextBox ID="TextBoxName" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Address">
<ItemTemplate>
<asp:DropDownList ID="DropDownListAddress" runat="server" AutoPostBack="true">
<asp:ListItem Text="Select" Value="0"> </asp:ListItem>
<asp:ListItem Text="Address1" Value="1"> </asp:ListItem>
<asp:ListItem Text="Address2" Value="2"> </asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div>
<asp:Button ID="ButtonADD" runat="server" Text="Add" OnClick="ButtonADD_Click" />
</div>
</form>
And this is my output
This is my CodeBehind
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("Name", typeof(string)));
dt.Columns.Add(new DataColumn("Address", typeof(string)));
dr = dt.NewRow();
dr["Name"] = string.Empty;
dr["Address"] = string.Empty;
dt.Rows.Add(dr);
ViewState["StudentTable"] = dt;
gvStudent.DataSource = dt;
gvStudent.DataBind();
}
protected void ButtonADD_Click(object sender, EventArgs e)
{
//Add Rows
}
}
}
There are 3 stpes to do it:
Get data from GridView and save to datatable
Add new row to datatable and save datatable to viewstate
Bind datatable to gridview
private void SaveGridViewDataIntoDataTable()
{
DataTable StudentTable = ViewState["StudentTable"] as DataTable;
foreach (GridViewRow row in gvStudent.Rows)
{
//get ddl value
DropDownList DropDownListAddress = row.FindControl("DropDownListAddress") as DropDownList;
StudentTable.Rows[row.RowIndex]["Address"] = DropDownListAddress.SelectedValue;
//get name from textbox
TextBox TextBoxName = row.FindControl("TextBoxName") as TextBox;
StudentTable.Rows[row.RowIndex]["Name"] = TextBoxName.Text;
}
ViewState["StudentTable"] = StudentTable;
}
private void AddNewRowToGridView()
{
SaveGridViewDataIntoDataTable();
DataTable StudentTable = ViewState["StudentTable"] as DataTable;
StudentTable.Rows.Add("Name", "Select");
gvStudent.DataSource = StudentTable;
gvStudent.DataBind();
}
now subscribe to Gridview RowBound event
<asp:GridView ID="gvStudent" runat="server" AutoGenerateColumns="False" OnRowDataBound="gvStudent_RowDataBound">
also add "RowIndex" Attribute to any of your gridview controls
<asp:TextBox ID="TextBoxName" runat="server" RowIndex='<%# Container.DisplayIndex %>'></asp:TextBox>
Code behind:
protected void gvStudent_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//get name from textbox
TextBox TextBoxName = row.FindControl("TextBoxName") as TextBox;
//get ddl value
DropDownList DropDownListAddress = row.FindControl("DropDownListAddress") as DropDownList;
//get rowindex
int RowIndex = Convert.ToInt32(TextBoxName.Attributes["RowIndex"]);
//get datatable stored in viewstate
DataTable StudentTable = ViewState["StudentTable"] as DataTable;
//assign values to controls
TextBoxName.Text = StudentTable.Rows[RowIndex]["Name"].ToString();
DropDownListAddress.SelectedValue = StudentTable.Rows[RowIndex]["Address"].ToString();
}
}
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
Iam new to asp.net can anyone help me on this.
I want to make a dynamic grid in asp.net which have 5 drop down list binding from database
and on selection of first dropdownvalue second dropdown bind.and it has also add row & delete
row button.
<asp:UpdatePanel runat="server"><ContentTemplate>
<asp:GridView ID="grvparameterdetail" runat="server"
ShowFooter="True" AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333"
GridLines="None" OnRowDeleting="grvparameterDetails_RowDeleting"
>
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="SNo" />
<asp:TemplateField HeaderText="Company">
<ItemTemplate>
<asp:DropDownList DataSource='<%# bindcompany1() %>' DataTextField="Comp_Name" DataValueField="Comp_Code" ID="drpcompany" runat="server" AppendDataBoundItems="true" AutoPostBack="true" OnSelectedIndexChanged="drpcompany_indexedchanged">
<asp:ListItem Value="-1">Select</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Center">
<ItemTemplate>
<asp:DropDownList DataSource='<%# bindunit1() %>' DataTextField="center" DataValueField="Pub_cent_Code" ID="drpcenter" runat="server" AppendDataBoundItems="true">
<asp:ListItem Value="-1">Select</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Publ.Type">
<ItemTemplate>
<asp:DropDownList DataSource='<%# bindptype1() %>' DataTextField="pubname" DataValueField="pubtypecode" ID="drppubtype" runat="server" AppendDataBoundItems="true">
<asp:ListItem Value="-1">Select</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Publication">
<ItemTemplate>
<asp:DropDownList ID="drppub" runat="server" AppendDataBoundItems="true">
<asp:ListItem Value="-1">Select</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edition">
<ItemTemplate>
<asp:DropDownList ID="drppubed" runat="server" AppendDataBoundItems="true">
<asp:ListItem Value="-1">Select</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server"
Text="Add New Row" OnClick="ButtonAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="True" />
</Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#EFF3FB" />
<EditRowStyle BackColor="#2461BF" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
aspx.cs code
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)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
//dr["Col2"] = string.Empty;
//dr["Col3"] = string.Empty;
//dr["Col4"] = string.Empty;
//dr["Col5"] = string.Empty;
dt.Rows.Add(dr);
ViewState["CurrentTable"] = dt;
grvparameterdetail.DataSource = dt;
grvparameterdetail.DataBind();
}
private void AddNewRow()
{
int rowIndex = 0;
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;
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
for (int i = 1; i <= dtCurrentTable.Rows.Count - 1; i++)
{
DropDownList Drpcompany =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[1].FindControl("drpcompany");
DropDownList drpcenter =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[2].FindControl("drpcenter");
DropDownList drppubtype =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[3].FindControl("drppubtype");
DropDownList Drppublication =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[4].FindControl("drppub");
DropDownList Drpedition =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[5].FindControl("drppubed");
//drCurrentRow = dtCurrentTable.NewRow();
//drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i]["Col1"] = Drpcompany.SelectedValue;
dtCurrentTable.Rows[i]["Col2"] = drpcenter.SelectedValue;
dtCurrentTable.Rows[i]["Col3"] = drppubtype.SelectedValue;
dtCurrentTable.Rows[i]["Col4"] = Drppublication.SelectedIndex;
dtCurrentTable.Rows[i]["Col5"] = Drpedition.SelectedValue;
rowIndex++;
}
//dtCurrentTable.Rows.Add(drCurrentRow);
//ViewState["CurrentTable"] = dtCurrentTable;
grvparameterdetail.DataSource = dtCurrentTable;
grvparameterdetail.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 Drpcompany =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[1].FindControl("drpcompany");
DropDownList drpcenter =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[2].FindControl("drpcenter");
DropDownList drppubtype =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[3].FindControl("drppubtype");
DropDownList Drppublication =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[4].FindControl("drppub");
DropDownList Drpedition =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[5].FindControl("drppubed");
Drpcompany.SelectedValue = dt.Rows[i]["Col1"].ToString();
drpcenter.SelectedValue = dt.Rows[i]["Col2"].ToString();
drppubtype.SelectedValue = dt.Rows[i]["Col3"].ToString();
Drppublication.SelectedValue = dt.Rows[i]["Col4"].ToString();
Drpedition.SelectedValue = dt.Rows[i]["Col5"].ToString();
rowIndex++;
}
}
}
}
protected void grvparameterDetails_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;
grvparameterdetail.DataSource = dt;
grvparameterdetail.DataBind();
for (int i = 0; i < grvparameterdetail.Rows.Count - 1; i++)
{
grvparameterdetail.Rows[i].Cells[0].Text = Convert.ToString(i + 1);
}
SetPreviousData();
}
}
}
private void SetRowData()
{
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 Drpcompany =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[1].FindControl("drpcompany");
DropDownList drpcenter =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[2].FindControl("drpcenter");
DropDownList drppubtype =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[3].FindControl("drppubtype");
DropDownList Drppublication =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[4].FindControl("drppub");
DropDownList Drpedition =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[5].FindControl("drppubed");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Col1"] = Drpcompany.SelectedValue;
dtCurrentTable.Rows[i - 1]["Col2"] = drpcenter.SelectedValue;
dtCurrentTable.Rows[i - 1]["Col3"] = drppubtype.SelectedValue;
dtCurrentTable.Rows[i - 1]["Col4"] = Drppublication.SelectedValue;
dtCurrentTable.Rows[i - 1]["Col5"] = Drpedition.SelectedValue;
rowIndex++;
}
ViewState["CurrentTable"] = dtCurrentTable;
//grvStudentDetails.DataSource = dtCurrentTable;
//grvStudentDetails.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
//SetPreviousData();
}
protected void drpcompany_indexedchanged(object sender, EventArgs e)
{
//what to write here
}
Thanks in advance.
I have made a sample code , it wil be easy to get an idea how to start ur task..
i have done harcoded data.. instead of hardcoding use the data from db..
chk the comments ...
Page 1 : aspx file
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="jquery.js.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td>Last Name</td>
<td>
<asp:TextBox ID="txtLastName" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>Speciality</td>
<td>
<asp:DropDownList ID="ddlSpeciality" runat="server">
<asp:ListItem Text="" />
<asp:ListItem Text="aaa" />
<asp:ListItem Text="bbb" />
<asp:ListItem Text="ccc" />
</asp:DropDownList></td>
</tr>
<tr>
<td>Location</td>
<td>
<asp:DropDownList ID="ddlLocation" runat="server">
<asp:ListItem Text="" />
<asp:ListItem Text="bangalore" />
<asp:ListItem Text="chennai" />
<asp:ListItem Text="hyderabad" />
</asp:DropDownList></td>
</tr>
<tr>
<td colspan="2" align="center">
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" /></td>
</tr>
</table>
</form>
</body>
</html>
Page 1: cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSearch_Click(object sender, EventArgs e)
{
string lastName = txtLastName.Text.Trim();
string speciality = ddlSpeciality.Text;
string location = ddlLocation.Text;
Response.Redirect(string.Format("page2.aspx?lastname={0}&speciality={1}&location={2}",lastName ,speciality , location));
}
}
}
Page 2: aspx file
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="page2.aspx.cs" Inherits="WebApplication1.test" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvdata" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkID" OnClick="LinkButton1_Click" Text="Details" runat="server"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Page 2: cs file
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack) { }
else
{
string lastname = Request.QueryString["lastname"];
string speciality = Request.QueryString["speciality"];
string location = Request.QueryString["location"];
string query = lastname.Length == 0 ? "" : "lastname ='" + lastname + "' and";
query += speciality.Length == 0 ? "" : "speciality ='" + speciality + "' and";
query += location.Length == 0 ? "" : "location ='" + location + "' ";
query = query.Trim().TrimStart(new char[] { 'a', 'n', 'd' }).TrimEnd(new char[] { 'a', 'n', 'd' });
query = "select * from tablename where " +( query.Length == 0 ? "1=1" : query);
// use this query to get data from sql database
// use shld get the data from db
// for example, i have hardcoded the datatable with some values
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("lastname", typeof(string));
dt.Columns.Add("speciality", typeof(string));
dt.Columns.Add("location", typeof(string));
dt.Rows.Add(1, "karthik", "aaa", "bangalore");
dt.Rows.Add(2, "parthip", "aaa", "chennai");
dt.Rows.Add(3, "krishna", "aaa", "hyderabad");
gvdata.DataSource = dt;
gvdata.DataBind();
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
string id = ((sender as LinkButton).Parent.Parent as GridViewRow).Cells[1].Text;
Response.Redirect("page3.aspx?id=" + id);
}
}
}
Page 3: aspx file
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="page3.aspx.cs" Inherits="WebApplication1.page3" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div runat="server" id="divcontent">
</div>
</form>
</body>
</html>
Page 3: cs file
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class page3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack) { }
else
{
string id = Request.QueryString["id"];
// use this id to fetch the data from db to get the details.
// get the data from db..
// i have hardcoded
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("lastname", typeof(string));
dt.Columns.Add("speciality", typeof(string));
dt.Columns.Add("location", typeof(string));
dt.Rows.Add(1, "karthik", "aaa", "bangalore");
Table tbl = new Table() { CellPadding=1 , CellSpacing=2 , BorderColor = System.Drawing.Color.Red, BorderWidth=1 };
foreach (DataColumn col in dt.Columns)
{
TableRow tr = new TableRow() { BorderWidth=1 , BorderColor = System.Drawing.Color.Red };
tr.Cells.Add( new TableCell () { BorderWidth=1 , BorderColor = System.Drawing.Color.Red ,Text = col.ColumnName});
tr.Cells.Add( new TableCell () { BorderWidth=1 , BorderColor = System.Drawing.Color.Red ,Text = dt.Rows[0][col].ToString()});
tbl.Rows.Add(tr);
}
divcontent.Controls.Add(tbl);
}
}
}
}
i am new to dotnet and am just trying out to add a row of text boxes for a grid view DYNAMICALLY.
On load of the page the grid view will be loaded with data as read only.
on clicking edit button, 2nd row will be loaded with text boxes. i succeeded till here. now on entering some data on these text boxes am not able to read the value back in my c# code.
here is my code snippet. can anyone please help me in this.
ASP code:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="justGrid._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<br />
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
<br />
<asp:TextBox ID="TextBox1" runat="server" Width="170px"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="edit" />
<br />
<br />
<asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="save" />
<br />
</asp:Content>
C# code:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
staticTable();
}
bindGrid();
}
protected void staticTable()
{
string[] NamesArray = new string[] { "RAM", "SAM", "TOM", "JERRY" };
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt = ds.Tables.Add();
dt.Columns.Add("Names", typeof(string));
for (int j = 1; j <= 5; j++)
{
dt.Columns.Add("" + j, typeof(string));
}
foreach (string l in NamesArray)
{
dt.Rows.Add(l);
}
dt.Rows[0][1] = "S";
dt.Rows[0][2] = "P";
dt.Rows[0][5] = "P";
dt.Rows[1][2] = "S";
dt.Rows[1][4] = "P";
dt.Rows[2][3] = "S";
dt.Rows[3][1] = "U";
dt.Rows[3][5] = "P";
ViewState["CurrentTable"] = dt;
GridView1.DataSource = ds;
// GridView1.DataBind();
}
protected void bindGrid()
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
GridView1.DataSource = dtCurrentTable;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
for (int k = 1; k <= 5; k++)
{
TextBox tb1 = new TextBox();
tb1.Attributes.Add("runat", "server");
tb1.Width = 15;
tb1.ID = "TBID" + k;
tb1.Text = GridView1.Rows[1].Cells[k].Text.Trim().Replace(" ", string.Empty);
GridView1.Rows[1].Cells[k].Controls.Add(tb1);
}
}
protected void Button2_Click(object sender, EventArgs e)
{
TextBox box1 = (TextBox)GridView1.Rows[1].Cells[1].FindControl("TBID1");
TextBox1.Text = box1.Text;
}
}
Note: for testing purpose alone..am trying to display the 2nd row 1st column value in textbox.
foreach (GridViewRow row in GridView1.Rows)
{
TextBox box1 = row.FindControl("TBID") as TextBox;
if (box1 != null)
{
string value = box1.Text;
}
}