Add Row to ASP.NET GridView? - c#

I have the following GridView which has a couple DropDownLists and TextBoxes. How can I add a new row to it, while persisting the existing GridView. I would like to Add the New row with the LinkButton. I am not using DataSource Controls and the GridView is currently populated via a DataTable. Here is the GridView:
<asp:LinkButton ID="btnAdd" runat="server" Text="Add Room"
onclick="btnAdd_Click"></asp:LinkButton>
<asp:GridView ID="gvRP" runat="server" AutoGenerateColumns="false"
onrowdatabound="gvRP_RowDataBound"
onrowediting="gvRP_RowEditing">
<Columns>
<asp:TemplateField HeaderText="Room" ItemStyle-Width="100%">
<ItemTemplate>
<asp:Label runat="server" Text="Room"></asp:Label>
<asp:DropDownList ID="ddlRoom" runat="server" AutoPostBack="True" DataTextField="Name"
DataValueField="Id" AppendDataBoundItems="true" OnSelectedIndexChanged="ddlRoom_SelectedIndexChanged">
<asp:ListItem Value="-1">Select...</asp:ListItem>
</asp:DropDownList>
<asp:Label runat="server" AssociatedControlID="ddlRate" Text="Rate" ID="lblRate"></asp:Label><asp:DropDownList
ID="ddlRate" runat="server" AppendDataBoundItems="true" DataTextField="Name"
DataValueField="Id">
<asp:ListItem Value="-1">Select...</asp:ListItem>
</asp:DropDownList>
<asp:Label runat="server" Text="Adults"></asp:Label>
<asp:TextBox ID="txtAdults" Text='<%#Bind("Adults") %>' runat="server" Width="25px"></asp:TextBox>
<asp:Label runat="server" Text="Children"></asp:Label>
<asp:TextBox ID="txtChildren" Text='<%#Bind("Children") %>' runat="server" Width="25px"></asp:TextBox>
<asp:Label runat="server" Text="Check In"></asp:Label>
<asp:TextBox ID="txtCheckIn" Text='<%#Bind("CheckIn") %>' runat="server" Width="75px"></asp:TextBox>
<asp:Label runat="server" Text="Check Out"></asp:Label>
<asp:TextBox ID="txtCheckOut" Text='<%#Bind("CheckOut") %>' runat="server" Width="75px"></asp:TextBox>
<h3>Rates</h3>
<asp:GridView ID="gvR" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Rate" />
<asp:BoundField DataField="Effective" HeaderText="Effective" />
<asp:BoundField DataField="Expire" HeaderText="Expire" />
<asp:BoundField DataField="Amount" HeaderText="Amount" />
<asp:BoundField DataField="Code" HeaderText="Currency" />
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Usually I try and do an example, but this one is quite thorough, and I don't "think" the url is going anywhere. Please refer to this link for a comprehensive example.
Here's the important code.
grid
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" />
</FooterTemplate>
code behind
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
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
//Set Previous Data on Postbacks
SetPreviousData();
}

Put Label control or Textbox as you like inside ItemTemplate if you put it at last it'll be displayed at last, for example
<ItemTemplate>
....
<asp:Label Text="foo" runat="server" />
</ItemTemplate>
or
<ItemTemplate>
<asp:Label Text="foo" runat="server" />
....
</ItemTemplate>

I decided to go with this solution:
DataTable dt = new DataTable();
DataColumn dcRoom = new DataColumn("Room", typeof(DropDownList));
DataColumn dcAdults = new DataColumn("Adults", typeof(string));
DataColumn dcChildren = new DataColumn("Children", typeof(string));
DataColumn dcCheckIn = new DataColumn("CheckIn", typeof(string));
DataColumn dcCheckOut = new DataColumn("CheckOut", typeof(string));
dt.Columns.AddRange(new DataColumn[] { dcRoom, dcAdults, dcChildren, dcCheckIn, dcCheckOut });
dt.Rows.Add(new object[] { new DropDownList(), "", "", "", "" });
gvRP.DataSource = dt;
gvRP.DataBind();
How does it know What to put in the DropDown (Select...) and I haven't specified two DropDowns, yet it still puts the second DropDown.

namespace gridview_row_add
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
DataGridViewTextBoxColumn columntype = new DataGridViewTextBoxColumn();
columntype.HeaderText = "Type";
columntype.Width = 80;
dataGridView1.Columns.Add(columntype);
DataGridViewTextBoxColumn columnparameters = new DataGridViewTextBoxColumn();
columnparameters.HeaderText = "Parameters";
columnparameters.Width = 320;
dataGridView1.Columns.Add(columnparameters);
DataGridViewTextBoxColumn columndisplay = new DataGridViewTextBoxColumn();
columndisplay.HeaderText = "Display";
columndisplay.Width = 150;
dataGridView1.Columns.Add(columndisplay);
DataGridViewTextBoxColumn enumuration = new DataGridViewTextBoxColumn();
enumuration.HeaderText = "Format";
enumuration.Width = 90;
dataGridView1.Columns.Add(enumuration);
dataGridView1.AllowUserToAddRows = false;//please add this if u don't want to add exta rows or else make it true.
}
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.Rows.Add();//here on each click the new row will be added.
int rowcount = dataGridView1.Rows.Count;
dataGridView1.Rows[rowcount - 1].Cells[0].Value = "data" + rowcount.ToString();
dataGridView1.Rows[rowcount-1].Cells[1].Value = "field";
dataGridView1.Rows[rowcount-1].Cells[2].Value = "xyzzz";
dataGridView1.Rows[rowcount-1].Cells[3].Value = "hts";
rowcount++;
}
}
}
this code works fine for me. in this code i added four headers in girdview, you can change them as per your requirement..one button click it will add new row first then data got filled in that row..
hope this will work for you..

Related

How to remove a row from gridview on Row Command?

I have a grid view where data is dyanmically added. I need an onRowCommand where the selected row will be deleted. I need the row to be deleted only from the grid view.
protected void LoadDataTable()
{
string header = lblHeader.Text;
string aa = tv.SelectedNode.Parent.Value;
string child = tv.SelectedNode.Text;
string parent = tv.SelectedNode.Parent.Text;
var dt = new DataTable();
dt.Columns.Clear();
dt.Rows.Clear();
dt.Columns.Add("TargetGLId");
dt.Columns.Add("TargetHead");
dt.Columns.Add("Parent");
dt.Columns.Add("Header");
foreach (GridViewRow row in gvBudgetSetup.Rows)
{
var lblheader = (Label)row.FindControl("lblHeader");
var lblparticular = (Label)row.FindControl("lblParticular");
var lblGlId = (Label)row.FindControl("lblGLId");
var lblparent = (Label)row.FindControl("lblParent");
var dr = dt.NewRow();
dr["TargetHead"] = lblparticular.Text;
dr["TargetGLID"] = lblGlId.Text;
dr["Parent"] = lblparent.Text;
dr["Header"] = lblHeader.Text;
dt.Rows.Add(dr);
}
var dr1 = dt.NewRow();
dr1["TargetHead"] = child;
dr1["TargetGLID"] = tv.SelectedValue;
dr1["Parent"] = parent;
dr1["Header"] = header;
dt.Rows.Add(dr1);
gvBudgetSetup.DataSource = null;
gvBudgetSetup.DataBind();
gvBudgetSetup.DataSource = dt;
gvBudgetSetup.DataBind();
}
I have tried this code to delete the row but it is not working.
protected void gvBudgetSetup_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete1")
{
// gvBudgetSetup.DeleteRow(e.Row.RowIndex);
GridViewRow gvr = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
int getRowIndex = gvr.RowIndex;
gvBudgetSetup.DeleteRow(getRowIndex);
}
}
This is the Gridview created. The gridview is not connected to any database. The data in the gridview is added from the back-end codes.
<asp:GridView ID="gvBudgetSetup" runat="server" CssClass="table1" AutoGenerateColumns="false" ShowFooter="true" OnSelectedIndexChanged="gvBudgetSetup_SelectedIndexChanged"
ShowHeaderWhenEmpty="true" OnRowDataBound="gvBudgetSetup_RowDataBound" OnRowCommand="gvBudgetSetup_RowCommand" OnRowDeleting="gvBudgetSetup_RowDeleting" Width="100%">
<FooterStyle CssClass="GridFooter" />
<RowStyle CssClass="GridItem" />
<columns>
<asp:TemplateField HeaderText="Sn">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="GL Id">
<ItemTemplate>
<asp:Label ID="lblGLId" runat="server" Text='<%# Bind("TargetGLID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header">
<ItemTemplate>
<asp:Label ID="lblHeader" runat="server" Text='<%# Bind("Header") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Parent">
<ItemTemplate>
<asp:Label ID="lblParent" runat="server" Text='<%# Bind("Parent") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Child">
<ItemTemplate>
<asp:Label ID="lblParticular" runat="server" Text='<%# Bind("TargetHead") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:LinkButton runat="server" Text="Delete" CommandName="Delete1"
ID="lnkDelete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</columns>
<EmptyDataTemplate>
"There are no data to display..."
</EmptyDataTemplate>
</asp:GridView>
Better way to do is have a flag in the data source that one row is flagged(deleted) and bind it again. To delete a datarow from a GridViewEvent, you have to re bind the datasource again.
Introduce a Flag column in your data source
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
//Update the flag in datasource using the CommandArgument value
//Bind the datasource again.
}
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
int getRowIndex = gvr.RowIndex;
gvBudgetSetup.DeleteRow(getRowIndex);
Use this updated code

asp.net C# gridview count always zero

I created a button (called "SubmitButtonTournamentName") that fills a gridview (called "GridViewTournaments") with information from a sql database (after i clicked on the button).
This gridview shows several data and includes two dropdownlists where I can choose information and a checkbox. Below the gridview is a submit button.
When I click on the button I like to have a validation. If I do not choose an option in one of the dropdown lists it should change its color.
This is my button handler that catches the button clicks:
public void BtnHandler(Object sender, EventArgs e) {
Button btn = (Button)sender;
switch (btn.CommandName) {
case "SubmitButtonTournamentName": {
//fill GridViewTournaments
// sql stuff...
try {
sqlConnection.Open();
IDataReader dr = idbCommand.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
GridViewTournaments.DataSource = dt;
GridViewTournaments.DataBind();
dr.Close();
} catch (Exception ex) {
System.Diagnostics.Debug.WriteLine("error: " + ex);
} finally {
sqlConnection.Close();
}
}
break;
case "btnSubmitEntry": {
//Here I try to validate the input
bool formError = false;
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[5] { new DataColumn("tourn_name"), new DataColumn("start_date"), new DataColumn("status"), new DataColumn("choice"), new DataColumn("doublePartner") });
int count = GridViewTournaments.Rows.Count;
System.Diagnostics.Debug.WriteLine("gridview count: " + count);
foreach (GridViewRow row in GridViewTournaments.Rows) {
if (row.RowType == DataControlRowType.DataRow) {
CheckBox chkEntry = (row.Cells[5].FindControl("chkEntry") as CheckBox);
if (chkEntry.Checked) {
DropDownList choice = (row.Cells[3].FindControl("ddlChoice") as DropDownList);
DropDownList doublePartner = (row.Cells[4].FindControl("ddlDoublePartner") as DropDownList);
if (choice.SelectedValue.Equals("-1")) {
formError = true;
choice.BackColor = Color.Red;
}
if (doublePartner.SelectedValue.Equals("-1")) {
formError = true;
doublePartner.BackColor = Color.Red;
}
string name = row.Cells[0].Text;
string startDate = row.Cells[1].Text;//(row.Cells[1].FindControl("lblCountry") as Label).Text;
string status = row.Cells[2].Text;
dt.Rows.Add(name, startDate, status, choice, doublePartner);
}
}
}
if (formError == false) {
Server.Transfer("ProccessEntry.aspx", true);
}
GridViewTournaments.DataSource = dt;
GridViewTournaments.DataBind();
}
break;
}
}
In case "btnSubmitEntry" is clicked I try to get the date from the gridview, change the color and rewrite the gridview with the changed elements.
This is my form:
<asp:GridView ID="GridViewTournaments" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="tourn_name" HeaderText="Name" ItemStyle-Width="150" />
<asp:BoundField DataField="start_date" HeaderText="Start date" ItemStyle-Width="150" />
<asp:BoundField DataField="status" HeaderText="Status" ItemStyle-Width="150" />
<asp:TemplateField HeaderText="choice">
<ItemTemplate>
<asp:Label ID="lblChoice" runat="server" Text='<%# Eval("choice") %>' Visible="false" />
<asp:DropDownList ID="ddlChoice" runat="server">
<asp:ListItem Text="Choose ..." Value="-1"></asp:ListItem>
<asp:ListItem Text="1st Choice" Value="1"></asp:ListItem>
<asp:ListItem Text="2nd Choice" Value="2"></asp:ListItem>
<asp:ListItem Text="3rd Choice" Value="3"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="doublePartner">
<ItemTemplate>
<asp:Label ID="lblDoublePartner" runat="server" Text='<%# Eval("doublePartner") %>' Visible="false" />
<asp:DropDownList ID="ddlDoublePartner" runat="server">
<asp:ListItem Text="Some name" Value="1"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Want to enter?">
<ItemTemplate>
<asp:Label ID="lblEnter" runat="server" Text='<%# Eval("enter") %>' Visible="false" />
<asp:CheckBox runat="server" ID="chkEntry" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnSubmitEntry" runat="server" Text="Submit" CommandName="btnSubmitEntry" OnClick="BtnHandler" />
The problem:
The foreach loop does not goes trough the gridview because it appears that there are zero rows in it.
I tested the code and this returns zero:
GridViewTournaments.Rows.Count
What I think is, that the "GridViewTournaments" is not binded the to page context so the button handler does not get the information from the gridview.
I know the button reloads the page but I like to get around the postback.
Maybe my solution is unconventionel so please tell me if I am totally be wrong.
When you bind your GridView you should wrap it around a if(!Page.IsPostBack){} to make sure that it only gets bound when the page loads and not on every single post back.Also, below is a complete working example of what you're trying to achieve:
Code behind:
public class User
{
public int ID { get; set; }
public string Name { get; set; }
}
public partial class GridViewValidation : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.BindData();
}
}
private void BindData()
{
var u1 = new User { ID = 1, Name = "User1" };
var u2 = new User { ID = 2, Name = "User2" };
GridView1.DataSource = new List<User> { u1, u2 };
GridView1.DataBind();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
DropDownList doublePartner = (row.Cells[2].FindControl("ddlDoublePartner") as DropDownList);
doublePartner.BackColor = doublePartner.SelectedValue.Equals("-1") ? Color.Red : Color.Transparent;
}
}
}
}
.ASPX:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="ID" />
<asp:BoundField DataField="Name" />
<asp:TemplateField HeaderText="doublePartner">
<ItemTemplate>
<asp:DropDownList ID="ddlDoublePartner" runat="server">
<asp:ListItem Text="Value -1" Value="-1"></asp:ListItem>
<asp:ListItem Text="Value 1" Value="1"></asp:ListItem>
<asp:ListItem Text="Value 2" Value="2"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
Output:

Values getting Cleared after adding a new row in Grid

When i try to add a new row to the exsisting grid, my values are getting cleared. Using the Viewstate i maintain the Datatable thorought the page and Bind it to the Grid. Think the values are getting cleared during a postback.
// AddNewRow
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
int i;
if (dtCurrentTable.Rows.Count > 0)
{
for (i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
TextBox txtguide = (TextBox)grdreports.Rows[rowIndex].FindControl("txtAccNo");
drCurrentRow = dtCurrentTable.NewRow();
dtCurrentTable.Rows[i - 1]["txtAccNo"] = txtguide.Text;
rowIndex += 1;
}
drCurrentRow = dtCurrentTable.NewRow();
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
ViewState["rowcount"] = dtCurrentTable.Rows.Count;
grdreports.DataSource = dtCurrentTable;
grdreports.DataBind();
}
}
// aspx Page:
<asp:GridView ID="grdreports" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
S.No</HeaderTemplate>
<ItemTemplate>
<%#Container.DataItemIndex+1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Acc.No/Tel.No">
<ItemTemplate>
<asp:TextBox ID="txtAccNo" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "nvrGuide")%>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="AddNew" ShowHeader="false">
<ItemTemplate>
<asp:LinkButton ID="lbtnAddGuide" runat="server" CommandName="Add" Text="Add New"
OnClick="lbtnAddGuide_OnClick"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete" ShowHeader="false">
<ItemTemplate>
<asp:LinkButton ID="lbtnDeleteGuide" runat="server" CommandName="Delete" Text="Delete"
OnClick="lbtnDeleteGuide_OnClick"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Where am i going wrong?
My guess is, the names are different.
Which means,
The name
`Text='<%#DataBinder.Eval(Container.DataItem, "nvrGuide")%>'`
specified in the .aspx page is "nvrguide" but, the name in the .cs page
TextBox txtguide = (TextBox)grdreports.Rows[rowIndex].FindControl("txtAccNo");
is "txtAccNo". So i think the values you have binded as empty grid in .cs page is different from the .aspx page.
Kindly change it as same in both the pages.
Probably it should throw an error for this. Since the code is not totally shown i cant tel.
For page Postback use following code on page load event
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
foreach (GridViewRow row in GridView1.Rows)
{
((TextBox)row.FindControl("txtAccNo")).Text = Request.Form[((TextBox)row.FindControl("txtAccNo")).UniqueID];
}
}
}

Fill GridView with TextBoxes and Dropdownlist from DataTable

I have GridView:
<asp:GridView ID="MyGridView" runat="server" ShowFooter="true"
AutoGenerateColumns="False" Visible="True">
<Columns>
<asp:BoundField DataField="id" ItemStyle-HorizontalAlign="center"/>
<asp:BoundField DataField="fullName" />
<asp:TemplateField HeaderText="situation>">
<ItemTemplate>
<asp:DropDownList ID="dl_situation" runat="server" AppendDataBoundItems="true">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="procesVerbal">
<ItemTemplate>
<asp:TextBox ID="tbNr" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Data">
<ItemTemplate>
<asp:TextBox ID="tbDate" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Now I want to fill this Grid with data from database, I have one method that returns datatable with all my data
when I fill mygrid:
MyGridView.DataSource = dataTable;
MyGridView.Databind();
in this case all TextBoxes and DropDownList are null.
In the code below I'm trying to create a function that receives DataTable from database and populates gridview with data. How do I make a foreach statement for dataTable.Rows that will assign text values to TextBox elements and selectedIndex value to DropDownList?
protected bool FillGridWithData(DataTable dataTable)
{bool result;
try
{
foreach (GridViewRow row in MyGridView1.Rows)
{
if (row.RowType != DataControlRowType.DataRow) break;
var ddl = (DropDownList)row.FindControl("dl_situation");
if (ddl != null)
{
ddl.DataSource = PublicStatic.Situation;
ddl.DataTextField = PublicStatic.Name;
ddl.DataValueField = PublicStatic.Code;
ddl.DataBind();
ddl.Items.Insert(0, new ListItem(String.Empty, String.Empty));
ddl.SelectedIndex = //data from datatable;
}
var tb1 = (TextBox)row.FindControl("tbNr");
if (tb1 != null)
tb1.Text =//data from datatable;
var tb2 = (TextBox)row.FindControl("tbDate");
if (tb2 != null)
tb2.Text = //data from datatable;
}
result = true;
}
catch (Exception exception)
{
result = false;
}
return result;
}
The DataField attribute in the bound field must equal to the column name in the datatable.
For binding textboxes in the template field you can use the Eval or Bind Method.
Example:
<asp:TemplateField HeaderText="procesVerbal">
<ItemTemplate>
<asp:TextBox ID="tbNr" Text='<%# Eval("ColumnName") %>' runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
and for binding the dropdown in the gridview, you can use a separate sql datasource. and specify dropdownlist DataSourceID,DataTextField and DataValueField property.
Dropdownlist Example:
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="ddl" runat="server" DataSourceID="SqlDataSource1" DataTextField="ProductName" DataValueField="ProductID" ></asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" SelectCommand="SELECT [ProductName], [ProductID] FROM [Alphabetical list of products]"></asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
and if you want to bind the datasource from code behind then you can use RowDataBound event of gridview
protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
TextBox t = (TextBox)e.Row.FindControl("ControlID");
t.Text = "Some Text";
}
}

how to delete textboxes dynamically

cs code
protected void DeleteNewRowToGrid()
{
int rowIndex = 0;
if (ViewState["dtCurrentTable"] != null)
{
DataTable DeldtCurrentTable = (DataTable)ViewState["dtCurrentTable"];
DataRow drCurrentRow = null;
if (DeldtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i > DeldtCurrentTable.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");
DropDownList box2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("ddldatatype");
drCurrentRow = DeldtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i - 1;
drCurrentRow["Column1"] = box1.Text;
drCurrentRow["Column2"] = box2.Text;
//drCurrentRow["Column3"] = box3.Text;
rowIndex--;
}
//add new row to DataTable
DeldtCurrentTable.Rows.Remove(drCurrentRow);
//Store the current data to ViewState
ViewState["dtCurrentTable"] = DeldtCurrentTable;
//Rebind the Grid with the current data
Gridview1.DataSource = DeldtCurrentTable;
Gridview1.DataBind();
}
}
}
protected void ButtonDel_Click(object sender, EventArgs e)
{
DeleteNewRowToGrid();
}
aspx code
<asp:gridview ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Column Name">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<%-- <asp:TemplateField HeaderText="Header 2">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>--%>
<asp:TemplateField HeaderText="Data Type">
<ItemTemplate>
<asp:DropDownList ID="ddldatatype" runat="server">
<asp:ListItem>varchar</asp:ListItem>
<asp:ListItem>int</asp:ListItem>
<asp:ListItem>numeric</asp:ListItem>
<asp:ListItem>uniqueidentifier</asp:ListItem>
<asp:ListItem>char</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click"/>
<asp:Button ID="ButtonDel" runat="server" Text="Delete Row" OnClick="ButtonDel_Click"/>
<input type="hidden" runat="server" value="0" id="hiddencount" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:gridview>
I have done with add rwo, now I want to delete
you are trying to deleta a row "drCurrentRow" that's not even in your DataTable, because you created this drCurrentRow = DeldtCurrentTable.NewRow(); yourself and didn't even insert it (no use anyway).
You have to search the rows to delete from your source like this:
var toDel = DeldtCurrentTable.Where(row => /* true if found */).ToArray();
foreach(var t in toDel) DeldtCurrentTable.Rows.Remove(t);
and then you can reiterate and set your rownumbers again.
Finaly set the the ViewState and the DataSource + DataBind it
BTW: your naming is really frustrating - what the heck does "DeleteNewRowToGrid" mean? Do you want to delete some new row? What is the a new row in this case?
So: Which row should be deleted here?

Categories