asp.net C# gridview count always zero - c#

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:

Related

Button onClick does not fire in GridView inside of TemplateField

I'm trying to write a code that would update only one record for the data.
I do not need to be able to update every field on the row, only one particular field.
I have page that defines a GridView as following:
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<UpdatePanel>
<ContentTemplate>
<fieldset style="width: 1%">
<legend>Search Customer</legend>
<table>
<tr>
<td>
<asp:DropDownList id="ddlSearchOption"
AutoPostBack="True"
OnSelectedIndexChanged="ddlSearchOption_SelectedIndexChanged"
runat="server">
<asp:ListItem Selected="True" Value="SearchBy"> Search By </asp:ListItem>
<asp:ListItem Value="CustID"> Customer ID </asp:ListItem>
<asp:ListItem Value="CustFirst"> First Name </asp:ListItem>
<asp:ListItem Value="CustLast"> Last Name </asp:ListItem>
<asp:ListItem Value="CustCity"> City </asp:ListItem>
</asp:DropDownList>
</td>
<asp:Panel id="pnlCustSearch" runat="server" >
<td>
<asp:Label id="lblEntry" runat="server" Text="" width="120px"></asp:Label>
</td>
<td>
<asp:TextBox id="txtSearchOptions" runat="server" width="50px">Hello</asp:TextBox>
</td>
<td>
<asp:Button id="btnFind" Text="Search" runat="server" onClick="btnFind_Click"></asp:Button>
</td>
</asp:Panel>
</tr>
</table>
</fieldset>
<div id ="msg">
<asp:Label id="lblMsg" runat="server" Text=""></asp:Label>
</div>
<div id="gridShow">
<asp:GridView ID="GridView1" runat="server" GridLines="None" AutoGenerateColumns="false"
AlternatingRowStyle-BackColor="#EEEEEE" EditRowStyle-BorderColor="Red">
<Columns>
<asp:TemplateField Visible="true" HeaderText="Customer ID">
<ItemTemplate>
<asp:Label runat="server" ID="lblCustID" Text='<%#Eval("CustID")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label runat="server" ID="lblFirstName" Text='<%#Eval("CustFirstName") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:Label runat="server" ID="lblLastName" Text='<%#Eval("CustLastName") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<ItemTemplate>
<asp:Label runat="server" ID="lblCity" Text='<%#Eval("CustCity") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtEmail" Text='<%#Eval("CustEmail") %>' />
<asp:Button runat="server" ID="btnUpdate" Text="Update" onClick="GridView1_btnUpdate_Click"/>
<asp:RequiredFieldValidator runat="server" ID="rfdCountry" ControlToValidate="txtEmail"
ValidationGroup="var1" ErrorMessage="*" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</ContentTemplate>
</UpdatePanel>
</asp:Content>
Then in codebehind I write the following:
protected void GridView1_btnUpdate_Click(Object sender, EventArgs e)
{
//Code goes here
}
When clicking button to update email nothing happens.
What am I doing wrong?
I tried to use one of suggestions here:
if (!IsPostBack)
{
GridView1.DataSource = App_Data.DataHandler.GetData("fname", "de");
GridView1.DataBind();
GridView1.Visible = true;
}
The data is displayed but the click event does not work anyway
I added the following to my GridView definition:
onrowcommand="GridView1_RowCommand"
and added the code suggested:
<asp:Button runat="server" ID="btnUpdate" Text="Update" CommandName="UpdateEmail"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"/>
In my .cs file I added the following:
protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "UpdateEmail")
{
//Get the index from the argument
int index = Convert.ToInt32(e.CommandArgument);
//Get the row
GridViewRow row = GridView1.Rows[index];
//Do whatever you need with your row here!
}
}
Still, click event does not fire.
Ok, here is my code behind .cs file:
public partial class index : System.Web.UI.Page
{
protected override object LoadPageStateFromPersistenceMedium()
{
return Session["__VIEWSTATE"];
}
protected override void SavePageStateToPersistenceMedium(object viewState)
{
Session["VIEWSTATE"] = viewState;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
Reset();
else
lblMsg.Text = "";
}
protected void Reset()
{
pnlCustSearch.Visible = false;
GridView1.Visible = false;
lblMsg.Text = "";
}
protected void ddlSearchOption_SelectedIndexChanged(object sender, EventArgs e)
{
Reset();
String ddlSelected = ddlSearchOption.SelectedValue;
if (ddlSelected != "")
{
ViewState["ddlSelected"] = ddlSelected;
pnlCustSearch.Visible = true;
SelectLabel(ddlSelected);
}
}
protected void SelectLabel(String choice)
{
switch (choice)
{
case "CustID":
lblEntry.Text = "Enter Customer ID";
break;
case "CustFirst":
lblEntry.Text = "Enter First Name";
break;
case "CustLast":
lblEntry.Text = "Enter Last Name";
break;
case "CustCity":
lblEntry.Text = "Enter City";
break;
default:
lblEntry.Text = "Enter Customer ID";
break;
}
}
protected void btnFind_Click(object sender, EventArgs e)
{
GridView1.Visible = true;
String option = (String)ViewState["ddlSelected"];
String input = txtSearchOptions.Text.Trim();
GridView1.DataSource = DataHandler.GetData(option,input);
GridView1.DataBind();
GridView1.Visible = true;
}
protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "UpdateEmail")
{
//Get the index from the argument
int index = Convert.ToInt32(e.CommandArgument);
//Get the row
GridViewRow row = GridView1.Rows[index];
//Do whatever you need with your row here!
}
}
protected void btnUpdate_Click(Object sender, EventArgs e)
{
String txt = null;
txt = "here";
}
}
When you try to handle events from GridView, you need to use a CommandName and a CommandArgument then handle the RowCommand event from the GridView.
See http://msdn.microsoft.com/... for reference.
ASP.Net page should look like :
<asp:ButtonField runat="server" ID="btnUpdate" Text="Update"
CommandName="UpdateEmail"
CommandArgument="<%# CType(Container,GridViewRow).RowIndex %>" />
In the RowCommand event :
if (e.CommandName == "UpdateEmail")
{
//Get the index from the argument
int index = Convert.ToInt32(e.CommandArgument);
//Get the row
GridViewRow row = GridView1.Rows[index];
//Do whatever you need with your row here!
}
I got it, finally. I had to change <asp:Button/> to
`<asp:ButtonField Text="Update Email" CommandName="UpdateEmail"`
and remove it from ItemTemplate.
But why this was a problem. What I wanted to do is just to display textfield in the same itemtemplate with button?
Actually, the answer was much easier then I thought originally. I just used different values to set session: __VIEWSTATE and VIEWSTATE
protected override object LoadPageStateFromPersistenceMedium()
{
return Session["__VIEWSTATE"];
}
protected override void SavePageStateToPersistenceMedium(object viewState)
{
Session["VIEWSTATE"] = viewState;
}
As soon as I changed it, button was able to fire events.
Thank you

Dynamic postbackurl

I'm having a problem calling a modal in asp
I need to set the postbackurl of linkbutton4 from code behind depending on what is selected in the dropdownlist! I have tried putting the postbackurl directlty on the linkbuttons tag it worked but when i change it from the code behind it doesnt BTW i change it when the link button is clicked.
Code behind for the linkbutton:
protected void LinkButton4_Click(object sender, EventArgs e)
{
var a = (Control)sender;
GridViewRow row = (GridViewRow)a.NamingContainer;
string b = row.Cells[0].Text;
Session["C"] = b;
DropDownList ddl =(DropDownList)row.Cells[7].FindControl("DropDownList1");
Session["D"] = ddl.SelectedItem.Text;
LinkButton lb = (LinkButton)row.Cells[7].FindControl("LinkButton4");
if (Session["D"].ToString() == "Upload")
{
lb.PostBackUrl = "preprod_design.aspx#edit";
// Upload();
}
if (Session["D"].ToString() == "Download")
{
Download();
}
infogridbind();
}
Here is the code for aspx :
<asp:GridView ID="GridView2" runat="server" ondatabound="GridView2_DataBound"
onrowdatabound="GridView2_RowDataBound"
onrowcreated="GridView2_RowCreated"
onselectedindexchanged="GridView2_SelectedIndexChanged"
onrowcommand="GridView2_RowCommand" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="SizeSetID" SortExpression="SizeSetID"/>
<asp:BoundField DataField="Revision No." SortExpression="RevisionNo" HeaderText = "Revision No."/>
<asp:TemplateField HeaderText ="Image">
<ItemTemplate>
<asp:Image ID="Image2" runat="server" onError = "this.style.display = 'none';" ImageUrl='<%#"~/ClientPoImage.ashx?autoId="+Eval("[SizeSetID]")%>' Width="50px" Height="40px"/>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Size Name" SortExpression="SizeName" HeaderText = "Size Name"/>
<asp:BoundField DataField="Quantity Requested" SortExpression="QuantityRequested" HeaderText ="Quantity Requested"/>
<asp:BoundField DataField="Quantity Received" SortExpression="QuantityReceived" HeaderText="Quantity Received"/>
<asp:BoundField DataField="Balance" SortExpression="Balance" HeaderText="Balance"/>
<asp:TemplateField HeaderText="Action">
<ItemTemplate >
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true">
<asp:ListItem>Upload</asp:ListItem>
<asp:ListItem>Download</asp:ListItem>
<asp:ListItem>Edit</asp:ListItem>
<asp:ListItem>Delete</asp:ListItem>
<asp:ListItem>Request</asp:ListItem>
<asp:ListItem>Receive</asp:ListItem>
</asp:DropDownList>
<asp:LinkButton ID="LinkButton4" runat="server" onclick="LinkButton4_Click">GO</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You can change PostBackUrl for LinkButton inside DropDownList.SelectedIndexChanged event like this
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
var ddl = (DropDownList)sender;
var row = (GridViewRow)(ddl.NamingContainer);
var lb = (LinkButton)row.FindControl("LinkButton4");
if (ddl.SelectedValue == "Upload")
{
lb.PostBackUrl = "preprod_design.aspx#edit";
}
if (ddl.SelectedValue == "Download")
{
....
}
}
also you need change markup like this
....
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true"
onselectedindexchanged="DropDownList1_SelectedIndexChanged" >
....
Remove AutoPostBack="True" From DropDownList, and in the header of page <%# Page Title="data"... EnableEventValidation="false" %>
After That You just go to click event of Link button and then
GridViewRow gr = (GridViewRow)(((LinkButton)sender).NamingContainer);
DropDownList ddl = (DropDownList)gr.FindControl("DropDownList1");
If(ddl.SelectedValue =="Upload") // or u can use ddl.SelectedItem.Text
{
//Upload();
}
else if(ddl.SelectedValue == "Download")
{
//Download();
}

Dropdown in dataview

In my GridView, I have the following columns:
<Columns>
<asp:BoundField DataField="report_type" HeaderText="Report Type"
SortExpression="report_type" />
<asp:BoundField DataField="progress" HeaderText="Progress"
SortExpression="progress" />
<asp:TemplateField HeaderText="..">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" DataValueField="progress">
<asp:ListItem Value="0">Incomplete</asp:ListItem>
<asp:ListItem Value="1">Complete</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
The progress column is just there for demo purposes which will eventually be removed. How do I get the value of the progress to select the correct itemlist in the dropdown?
So if the value of progress is 1, the dropdown should have Complete selected. If the value of the progress is 0, the dropdown should have Incomplete selected.
Add a OnRowDataBound attribute to the gridview in the .aspx page:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="id" OnRowDataBound="GridViewRowEventHandler">
Replace
<asp:BoundField DataField="Progress" HeaderText="Progress"
SortExpression="progress" />
with
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="progress_Flags" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Progress").ToString()%>'/>
</ItemTemplate>
</asp:TemplateField>
In the code behind:
protected void GridViewRowEventHandler(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label flag = (Label)e.Row.FindControl("progress_Flags");
DropDownList myDropDown = (DropDownList)e.Row.FindControl("DropDownList1");
if (flag.Text == "1")
{
myDropDown.SelectedValue = "1";
}
//add more conditions here..
}
}
In RowDataBound event you can use e.Row.FindControl
protected void GridView_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
GridViewRow row = e.Row;
DataRowView dr = row.DataItem as DataRowView;
// now find the control in the row by control ID
DropDownList myDropDown = row.FindControl("DropDownList1") as DropDownList;
}

Add Row to ASP.NET GridView?

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..

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