How to bulk edit a single column in a grid view - c#

I am working on an ASP.net application ( c#) . In it I have a grid view with columns displayed as ItemTemplates. I want to edit the values of one column.
I have an update button below the grid view. So when I click on update, the new values should be updated to the database.
I am using a list collection to bind the data to grid view.
I have no idea how to accomplish this.

Lets say you have TextBox inside the column, where the user is going to update new values. You can iterate through the gridview rows, in this manner
foreach(GridViewRow row in GridView1.Rows) {
if(row.RowType == DataControlRowType.DataRow) {
TextBox txtbx= row.FindControl("txtbx") as TextBox;
//using the txtbx you can get the new values and update then to the db
}
}

foreach(GridViewRow row in GridView1.Rows)
{
if(row.RowType == DataControlRowType.DataRow)
{
String str = ((txtbx)(row.Cells[2].Controls[0])).Text;
}
}
Check your cell value for textbox.

If you are using a GridView, are you also using a backing object (some sort of collection) to bind to the grid rows - it seems likely since you are using ItemTemplates to display them.
In this case, can you access the items you wish to change from this backing collection?
EDIT
Comment says that you're using a list to bind the grid, so why not make your changes to the list items and send those back to the database?
foreach(var listItem in MyList)
{
listItem.ThingToChange = newValueForThisProperty;
}
SubmitChangesToDatabase(MyList);

I created a full working demo and tested it:
GridBulkEdit.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="GridBulkEdit.aspx.cs" Inherits="GridBulkEdit" EnableViewState="true" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<% /*1. Enter the new value for the column to be updated in the 'NewValue' textbox
2. Check the 'UpdateThisRow' checkbox in the gridview for all rows that need to be updated.
3. Click the 'Update' button */%>
New Value: <asp:TextBox runat="server" ID="NewValue_TextBox"></asp:TextBox>
<asp:Button runat="server" ID="Update_Button" Text="Update Checked Rows With New Value" OnClick="Update_Button_Click" />
<% /* Assuming grid is bound to datasource with 2 columns:
1. 'PrimaryKeyField' - the primary key for each row
2. 'CurrentValue' - the value that we want to batch update */%>
<asp:GridView runat="server" ID="grid" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField runat="server" ID="PrmaryKeyForThisRow_HiddenField" Value='<%# Bind("PrimaryKeyField") %>' />
<asp:CheckBox runat="server" ID="UpdateThisRow_CheckBox" Checked="false" ToolTip="Check this box to update this row"/>
<asp:Label runat="server" ID="CurrentValue_Label" Text='<%# Bind("CurrentValue") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label runat="server" ID="TestOutput_Label"></asp:Label>
</form>
</body>
</html>
GridBulkEdit.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using System.Data;
public partial class GridBulkEdit : System.Web.UI.Page
{
protected void Page_PreInit(object sender, EventArgs e)
{
//Create a data table to bind the grid
DataTable DT = new DataTable();
DT.Columns.Add("PrimaryKeyField");
DT.Columns.Add("CurrentValue");
DataRow DR1 = DT.NewRow();
DR1["PrimaryKeyField"] = 1;
DR1["CurrentValue"] = "value one";
DT.Rows.Add(DR1);
DataRow DR2 = DT.NewRow();
DR2["PrimaryKeyField"] = 2;
DR2["CurrentValue"] = "value two";
DT.Rows.Add(DR2);
DataRow DR3 = DT.NewRow();
DR3["PrimaryKeyField"] = 3;
DR3["CurrentValue"] = "value three";
DT.Rows.Add(DR3);
grid.DataSource = DT;
grid.DataBind();
}
protected void Update_Button_Click(object sender, EventArgs e)
{
TestOutput_Label.Text = "";
for (int i = 0; i < grid.Rows.Count; i++)
{
HiddenField PrmaryKeyForThisRow_HiddenField = grid.Rows[i].FindControl("PrmaryKeyForThisRow_HiddenField") as HiddenField;
CheckBox UpdateThisRow_CheckBox = grid.Rows[i].FindControl("UpdateThisRow_CheckBox") as CheckBox;
if (UpdateThisRow_CheckBox.Checked)
{
UpdateRow(PrmaryKeyForThisRow_HiddenField.Value);
}
}
}
private void UpdateRow(object PrimaryKey)
{
object NewValue = NewValue_TextBox.Text;
//Execute SQL query to update row with the passed PrimaryKey with the NewValue
TestOutput_Label.Text += "<br/> Update row whose PrimaryKey is: " + PrimaryKey + " with new value: " + NewValue;
}
}

Related

How do I find the value of a checkbox from a gridview in asp/c#

I have had the most trouble with finding the value of a checkbox. I have searched everywhere and I can't seem to get it to the right value, nothing comes up or I get a NULL reference error. I have checked the other threads/posts and none seem to work.
All I'm trying to do is get the value of a checkbox, but I can't seem to do that.
The information is coming from a database. I can grab the string value but I can't grab the checkbox value.
Anyways, this is the code I used to get ahold of the string value and checkbox value:
//String grabber
Convert.ToString(gvOrders.SelectedRow.Cells[2].Text);
//Checkbox grabber
Boolean.TryParse(gvOrders.SelectedRow.Cells[11].Text, out bool pep);
or
//Checkbox grabber
Convert.ToBoolean(gvOrders.SelectedRow.Cells[2].Text);
Anyways, please no negativity, I've been struggling to find the value and it just isn't working.
Thanks in advance.
EDIT:
ADDED CODE:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToString(Session["username"]) != "Scott" || Convert.ToString(Session["perms"]) != "admin")
{
Response.Redirect("Default.aspx");
}
GuestOrderInfo temp = new GuestOrderInfo();
gvOrders.DataSource = temp.SearchAll();
gvOrders.DataBind();
}
protected void osicOrders(object sender, EventArgs e)
{
Int16 row = Convert.ToInt16(gvOrders.SelectedRow.Cells[1].Text);
Session["row"] = row;
//Convert to a session to use in a different function.
Session["fName"] = Convert.ToString(gvOrders.SelectedRow.Cells[2].Text);
Session["lName"] = Convert.ToString(gvOrders.SelectedRow.Cells[3].Text);
Session["street"] = Convert.ToString(gvOrders.SelectedRow.Cells[4].Text);
Session["street2"] = Convert.ToString(gvOrders.SelectedRow.Cells[5].Text);
Session["city"] = Convert.ToString(gvOrders.SelectedRow.Cells[6].Text);
Session["state"] = Convert.ToString(gvOrders.SelectedRow.Cells[7].Text);
Session["zip"] = Convert.ToString(gvOrders.SelectedRow.Cells[8].Text);
Session["price"] = Convert.ToDouble(gvOrders.SelectedRow.Cells[9].Text);
Session["size"] = Convert.ToString(gvOrders.SelectedRow.Cells[10].Text);
Session["pepperoni"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[11].Text, out bool pep);
Session["sausage"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[12].Text, out bool sau);
Session["meatball"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[13].Text, out bool mea);
Session["ham"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[14].Text, out bool hamm);
Session["peppers"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[15].Text, out bool pepp);
Session["onions"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[16].Text, out bool onio);
Session["spinach"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[17].Text, out bool spin);
Session["pineapple"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[18].Text, out bool pine);
Session["bbq"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[19].Text, out bool bbqq);
Session["xcheese"] = Boolean.TryParse(gvOrders.SelectedRow.Cells[20].Text, out bool xch);
//
//
//FIND OUT HOW TO GET THE VALUE OF A CHECKBOX IN GV AND USE THAT VALUE WITHIN SESSION VARIABLES TO UPDATE DATA IN THE UPDATE PAGE THEN MAKE A SEARCH PAGS
//
//
CheckBox cb = (CheckBox)gvOrders.SelectedRow.Cells[11].FindControl("pepperoni");
selectedID.Text = "Selected: " + Convert.ToString(row);
selectedInformation.Text = Session["fName"] + " " + Session["lName"] + " Pepp = " + cb.Checked;
edit.Visible = true;
delete.Visible = true;
selectedInformation.Visible = true;
cancel.Visible = true;
}
protected void delete_OnClick(object sender, EventArgs e)
{
string buttonText = (sender as LinkButton).Text;
if (buttonText == "Delete")
{
edit.Visible = false;
delete.Visible = false;
yes.Visible = true;
no.Visible = true;
sure.Visible = true;
}
if (buttonText == "Edit")
{
Response.Redirect("editOrders.aspx");
}
if (buttonText == "Yes")
{
GuestOrderInfo temp = new GuestOrderInfo();
temp.DeleteARecord(Convert.ToInt16(Session["row"]));
Session.Remove("row");
Response.Redirect("viewOrders.aspx");
}
if (buttonText == "No")
{
edit.Visible = true;
delete.Visible = true;
yes.Visible = false;
no.Visible = false;
sure.Visible = false;
}
if (buttonText == "Cancel")
{
Response.Redirect("viewOrders.aspx");
}
}
}
ORIGINAL HTML:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="viewOrders.aspx.cs" Inherits="Default2" %>
<asp:Content ID="Content1" ContentPlaceHolderID="title" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="BodyContent" Runat="Server">
<asp:GridView ID="gvOrders" runat="server" OnSelectedIndexChanged="osicOrders" AutoGenerateSelectButton="True" >
</asp:GridView>
<asp:Label runat="server" ID="selectedID"></asp:Label>
<asp:Label runat="server" ID="selectedInformation" Visible="False"/>
<asp:LinkButton runat="server" ID="edit" Text="Edit" OnClick="delete_OnClick" Visible="False"/> <asp:LinkButton runat="server" ID="delete" Text="Delete" Visible="False" OnClick="delete_OnClick"/><asp:LinkButton runat="server" ID="cancel" Text="Cancel" Visible="False" OnClick="delete_OnClick"/><br/>
<asp:Label runat="server" Text="Are you sure you want to do this?" ID="sure" Visible="False"></asp:Label><br/>
<asp:LinkButton runat="server" Visible="False" ID="no" Text="No" OnClick="delete_OnClick"/> <asp:LinkButton runat="server" Visible="False" ID="yes" Text="Yes" OnClick="delete_OnClick"/>
<!-- Make the edit button work along with the delete -->
<!-- Data validation, design and submit :^) -->
</asp:Content>
If you are using a CheckBoxField in your grid view as below, then the code for getting checkbox value is as given in second code snippet.
Checkbox column markup in GridView
<asp:CheckBoxField DataField="Discontinued" HeaderText="Discontinued"
SortExpression="Discontinued" />
Getting the checkbox value in code-behind
bool isChecked = (gvOrders.SelectedRow.Cells[11].Controls[0] as CheckBox).Checked;
However, if you are using a template column in your gridview, then you need to follow different approach that is explained below.
In your code-behind,
you need to first get the gridview's data row
and then find the checkbox control using the ID of the checkbox
control you specified in your html markup, which is CheckBox1 in
code sample below ( you don't need to bother about getting the cell containing checkbox in this case)
Templated Checkbox Column
<asp:TemplateField HeaderText="CheckBox Column">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Eval("Discontinued") %>' />
</ItemTemplate>
Getting the checkbox value in code-behind
bool isChecked = (gvOrders.SelectedRow.FindControl("CheckBox1") as CheckBox).Checked;
It's not clear what value you want to return from the CheckBox. Do you want to get the Checkbox label or selection status?
Anyway instead of trying to get the cell content directly, I think you should instead find the checkbox control like this.
CheckBox cb = (CheckBox)gvOrders.SelectedRow.Cells[2].FindControl("checkboxID");
string checkboxtext = cb.Text; //Gives you the text of the checkbox
bool IsCheckboxChecked = cb.Checked; // Gives you the selection status of the checkbox.
Is this what you're looking for?
Edit: I can see that you have not specified GridView.AutoGenerateColumns Property which means that it defaults to true. What that means is that the layout of the columns is decided by the data that is bound to the grid view. This can cause problems while debugging as the cell index you are giving may change depending on the data that is returned by the data reader. I would advise you to set AutoGenerateColumns to false and manually specify the layout that you want.
You can see an example here

Add row to inner repeater of nested repeaters at runtime c#

I am building a web application to construct a document. The document has paragraphs (outer repeater) and subparagraphs (inner repeater). What I'm looking for is a way to add a blank subparagraph to an existing document.
My markup:
<asp:Repeater ID="ParagraphRepeater" runat="server"
OnItemDataBound="ParagraphRepeater_ItemDataBound" >
<ItemTemplate>
<asp:TextBox ID="ParagraphTitleTextBox" runat="server" Font-Bold="true" Width="300px"
Text='<%# Eval("ParagraphTitle") %>'></asp:TextBox>
<br />
<asp:TextBox ID="ParagraphTextTextBox" runat="server" TextMode="MultiLine" Wrap="true"
width="1100px" Height="50px" Text='<%# Eval("ParagraphText") %>'></asp:TextBox>
<asp:Button ID="DeleteParagraphButton" runat="server" Text="Delete" OnClick="DeleteParagraphButton_Click" />
<asp:Repeater ID="SubParagraphRepeater" runat="server" DataSourceID="SubParagraphSqlDataSource">
<ItemTemplate>
<div style="margin-left: 30px">
<asp:TextBox ID="SubParagraphTitleTextBox" runat="server" Font-Underline="true" Width="200px"
Text='<%# Eval("SubParagraphTitle") %>'></asp:TextBox>
<br />
<asp:TextBox ID="SubParagraphTextTextBox" runat="server" TextMode="MultiLine" Wrap="true"
Width="1050px" Height="50px" Text='<%# Eval("SubParagraphText") %>'></asp:TextBox>
<asp:Button ID="DeleteSubParagraphButton" runat="server" Text="Delete"
OnClick="DeleteSubParagraphButton_Click" />
<br />
</div>
</ItemTemplate>
</asp:Repeater>
<br />
<br />
<br />
</ItemTemplate>
My code:
protected void MultiView1_ActiveViewChanged(object sender, EventArgs e)
{
if (MultiView1.GetActiveView() == InputView)
{
BuildParagraphDataTable();
BuildSubParagraphDataTable();
if (RevisionsDropDownList.SelectedValue == "0")
{
// User is creating a new document
// Call method to create a datatable for the form row
SetFormRow();
// Call method to create a datatable for the paragraph row
AddParagraph();
DataTable dt = (DataTable)ViewState["ParagraphTable"];
ParagraphRepeater.DataSource = dt;
ParagraphRepeater.DataBind();
}
else
{
// User is opening an existing document
// Get the formId and save it to ViewState
int formId = Convert.ToInt32(RevisionsDropDownList.SelectedValue);
ViewState["FormId"] = formId.ToString();
// Bind the Paragraph repeater to its sqlDataSource
ParagraphRepeater.DataSource = ParagraphSqlDataSource;
ParagraphRepeater.DataBind();
}
}
}
protected void AddParagraph()
{
int paragraphId;
DataTable dt = (DataTable)ViewState["ParagraphTable"];
DataRow dr = dt.NewRow();
if (ViewState["ParagraphId"] != null)
paragraphId = Convert.ToInt32(ViewState["ParagraphId"]);
else
paragraphId = 0;
paragraphId--;
int formId = Convert.ToInt32(ViewState["FormId"]);
dr["ParagraphId"] = paragraphId;
dr["FormId"] = formId;
dr["ParagraphTitle"] = string.Empty;
dr["ParagraphText"] = string.Empty;
dr["CreatorId"] = string.Empty;
dr["RevisorId"] = string.Empty;
dt.Rows.Add(dr);
ViewState["ParagraphTable"] = dt;
ViewState["ParagraphId"] = paragraphId;
}
protected void AddSubParagraph()
{
DataTable dt = (DataTable)ViewState["SubParagraphTable"];
DataRow dr = dt.NewRow();
int paragraphId = Convert.ToInt32(ViewState["ParagraphId"]);
dr["ParagraphId"] = paragraphId;
dr["SubParagraphTitle"] = string.Empty;
dr["SubParagraphText"] = string.Empty;
dr["CreatorId"] = string.Empty;
dr["RevisorId"] = string.Empty;
dt.Rows.Add(dr);
ViewState["SubParagraphTable"] = dt;
}
protected void ParagraphRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
AddParagraph();
DataTable parentDataTable = (DataTable)ViewState["ParagraphTable"];
DataRow lastDTRow = parentDataTable.Rows[parentDataTable.Rows.Count - 1];
int paragraphId = (int)ViewState["ParagraphId"];
DataRowView thisParagraphRowView = (DataRowView)e.Item.DataItem;
paragraphId = (int)thisParagraphRowView.Row["ParagraphId"];
lastDTRow["ParagraphId"] = thisParagraphRowView.Row["ParagraphId"];
lastDTRow["FormId"] = thisParagraphRowView.Row["FormId"];
lastDTRow["ParagraphTitle"] = thisParagraphRowView.Row["ParagraphTitle"];
lastDTRow["ParagraphText"] = thisParagraphRowView.Row["ParagraphText"];
ViewState["ParagraphTable"] = parentDataTable;
ViewState["ParagraphId"] = paragraphId.ToString();
DataTable childDataTable;
DataRowView thisSubParagraphRowView;
Repeater childRepeater = (Repeater)e.Item.FindControl("SubParagraphRepeater");
foreach (RepeaterItem item in childRepeater.Items)
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
thisSubParagraphRowView = (DataRowView)item.DataItem;
if (thisSubParagraphRowView != null)
{
AddSubParagraph();
childDataTable = (DataTable)ViewState["SubParagraphTable"];
lastDTRow = childDataTable.Rows[childDataTable.Rows.Count - 1];
lastDTRow["ParagraphId"] = thisSubParagraphRowView.Row["ParagraphId"];
lastDTRow["SubParagraphTitle"] = thisSubParagraphRowView.Row["SubParagraphTitle"];
lastDTRow["SubParagraphText"] = thisSubParagraphRowView.Row["SubParagraphText"];
ViewState["SubParagraphTable"] = childDataTable;
}
}
}
}
}
When the user opens an existing form, the itemDataBound code populates the datatables for the paragraphs and subparagraphs. (These datatables will be used in the update to the database.)
When the user creates a new form, the setForm() and addParagraph() methods are called to create the form ID and add a blank paragraph. No blank subparagraph is added - the user must click a button to do so.
As for the data model, there is one Form (the user selects it from a ddl). A Form can have 1 to many paragraphs, and paragraphs can have zero to many subparagraphs.
I need to create a blank row in the inner repeater for a particular row in the outer repeater (the paragraph that the cursor is currently located in, or if the cursor is located in a subparagraph, the parent paragraph). How do I do that? I've done a ton of digging on Google but cannot find an entry that addresses this issue. Thanks.
The answer is to move the "AddSubParagraph" button from a standalone position to be inside the outer repeater. That way, the repeater can be located by using the "NamingContainer" attribute of the button. Then it's a matter of finding the inner repeater Repeater innerRepeater = (Repeater)outerRepeater.FindControl("childRepeater");, and adding a row to it. I can add the row but I'm having trouble DataBinding the inner repeater.
What I do is keep datatables in viewstate for each repeater, and mirror the data between the repeaters and the datatables. When I need to add a row, I add it to the datatable and then databind the repeater to the datatable. But I get an error: The line it errors on is childRepeater.Datasource = dt;. The error is "DataSource and DataSourceId are both defined. Remove one definition." DataSourceId is defined on the childRepeater in the markup, pointing to a SQLDataSource. So I need to find a way to bind the inner repeater to its SQLDataSource at retrieval time, on the fly.
One snag: I'm thinking I'd use the ItemDataBound event to do the databinding. But I already have a lot of code there (see above). Is there another event I can use that makes sense?

How to hide column in GridView after DataBind?

I ask this question because I think I have different problem with this : How to hide gridview column after databind?
My gridview has data from database. I don't set any "td" in my code, but html changes the gridview to table and have "td". The problem is, I don't want the cell or "td" is shown on the page, I just want to receive the data in the cell to show the image in the database.
This is code to retrieve data from database:
public static DataTable FetchAllImagesInfo(int id)
{
string sb = "Select img_content, Img_id, csrid FROM images WHERE Img_Id = " + id + ";";
SqlConnection conn = DatabaseFactory.GetConnection();
SqlDataAdapter da = new SqlDataAdapter(sb, conn);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
This is codebehind to bind GridView, here I tried to set Visible to true or false, but it doesn't work. I set column index manually because it's only has 3 column :
GridView1.DataSource = ProductAllLocationCatalog.FetchAllImagesInfo(_id);
GridView1.DataBind();
GridView1.Columns[0].Visible = true;
GridView1.Columns[1].Visible = false;
GridView1.Columns[2].Visible = false;
And, this is my aspx code :
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField runat="server">
<ItemTemplate runat="server">
<asp:Image ID="image1" runat="server" ImageUrl='<%#"Handler.ashx?csrid="+Eval("csrid") %>' style="max-height:400px; max-width:940px; text-align:center; margin:auto; display:block;" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I just need the image from the database, not other. But if I only SELECT the image, gridview can not do DataBind(), and I can't get value of "csrid".
Thank you!
Try
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[1].Visible = false;
e.Row.Cells[2].Visible = false;
}
I believe the issue is that your GridView is automatically generating your columns, and the GridView.Columns property only stores explicitly declared columns. Instead of hiding the column, you can hide the cells comprising the columns you don't want when each row is bound. It seems like there should be a better way to handle this, but outside of using explicitly declared columns, I don't know one.

ASP.NET find control by id

I am doing a simple web site using asp.net and i am having troubles finding my or objects by id in the code behind in c#. I have something like this:
<asp:ListView ID="InternamentosListView" runat="server"
DataSourceID="InternamentosBD">
<LayoutTemplate>
<table id="camas">
<asp:PlaceHolder runat="server" ID="TablePlaceHolder"></asp:PlaceHolder>
</table>
</LayoutTemplate>
the rest is irrelevant, and then i use this in the code behind:
Table table = (Table)FindControl("camas");
i also tried:
Table table = (Table)camas;
and
Control table= (Table)FindControl("camas");
and each one of this lines gives me Null. am i doing something wrong ?
EDIT: From your answers i did this:
<LayoutTemplate>
<table id="camas" runat="server">
</table>
</LayoutTemplate>
and tried all the things stated above. same result.
EDIT2: Whole Code:
C#
protected void Page_Load(object sender, EventArgs e)
{
Table table = (Table)FindControl("camas");
HiddenField NCamasHF = (HiddenField)FindControl("NCamas");
int NCamas = Convert.ToInt32(NCamasHF);
HiddenField NColunasHF = (HiddenField)FindControl("NColunas");
HiddenField CorMasc = (HiddenField)FindControl("CorMasc");
HiddenField CorFem = (HiddenField)FindControl("CorFem");
int NColunas = Convert.ToInt32(NColunasHF);
TableRow Firstrow = new TableRow();
table.Rows.Add(Firstrow);
for (int i = 1; i <= NCamas; i++)
{
if (i % NColunas == 0)
{
TableRow row = new TableRow();
table.Rows.Add(row);
TableCell cell = new TableCell();
cell.BackColor = System.Drawing.Color.LightGreen;
cell.CssClass = "celula";
row.Cells.Add(cell);
}
else
{
TableCell cell = new TableCell();
cell.BackColor = System.Drawing.Color.LightGreen;
cell.CssClass = "celula";
Firstrow.Cells.Add(cell);
}
}
}
asp.net
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:SqlDataSource
ID="ParametrosBD"
ConnectionString ="<%$ ConnectionStrings:principal %>"
ProviderName = "System.Data.SqlClient"
SelectCommand = "SELECT par_Id, par_NCamas, par_NColunas, par_CorMasculino, par_CorFeminino FROM Parametros WHERE par_Id=1"
runat="server">
</asp:SqlDataSource>
<asp:ListView ID="InternamentosListView" runat="server"
DataSourceID="InternamentosBD">
<LayoutTemplate>
<table id="camas" runat="server">
</table>
</LayoutTemplate>
<ItemTemplate>
<asp:HiddenField ID="NCamas" runat="server" Value='<%# Bind("par_NCamas") %>' />
<asp:HiddenField ID="NColunas" runat="server" Value='<%# Bind("par_NColunas") %>' />
<asp:HiddenField ID="CorMasc" runat="server" Value='<%# Bind("par_CorMasculino") %>' />
<asp:HiddenField ID="CorFem" runat="server" Value='<%# Bind("par_CorFeminino") %>' />
<tr id="cama"></tr>
</ItemTemplate>
</asp:ListView>
</asp:Content>
To expand on #Yura Zaletskyy's recursive find control method from MSDN -- you can also use the Page itself as the containing control to begin your recursive search for that elusive table control (which can be maddening, I know, I've been there.) Here is a bit more direction which may help.
using System;
using System.Collections.Specialized;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI;
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Table table = (Table)FindControlRecursive(Page, "camas");
if (table != null)
{
//Do awesome things.
}
}
private Control FindControlRecursive(Control rootControl, string controlID)
{
if (rootControl.ID == controlID) return rootControl;
foreach (Control controlToSearch in rootControl.Controls)
{
Control controlToReturn = FindControlRecursive(controlToSearch, controlID);
if (controlToReturn != null) return controlToReturn;
}
return null;
}
}
As you already added runat="server" is step 1. The second step is to find control by id, but you need to do it recursively. For example consider following function:
private Control FindControlRecursive(Control rootControl, string controlID)
{
if (rootControl.ID == controlID) return rootControl;
foreach (Control controlToSearch in rootControl.Controls)
{
Control controlToReturn =
FindControlRecursive(controlToSearch, controlID);
if (controlToReturn != null) return controlToReturn;
}
return null;
}
None of the existing answers mention the obvious built-in solution, FindControl.
Detailed here, FindControl is a function that takes as a string the id of a control that is a child of the calling Control, returning it if it exists or null if it doesn't.
The cool thing is that you can always call it from the Page control which will look through all controls in the page. See below for an example.
var myTextboxControl = (TextBox)Page.FindControl("myTextboxControlID);
if (myTextboxControl != null) {
myTextboxControl.Text = "Something";
}
Note that the returned object is a generic Control, so you'll need to cast it before you can use specific features like .Text above.
You need to have runat="server" for you to be able to see it in the codebehind.
e.g.
<table id="camas" runat="server">
Ok. You have the table within a list view template. You will never find the control directly on server side.
What you need to do is find control within the items of list.Items array or within the item data bound event.
Take a look at this one- how to find control in ItemTemplate of the ListView from code behind of the usercontrol page?
When you're using a master page, then this code should work for you
Note that you're looking for htmlTable and not asp:Table.
// add the namespace
using System.Web.UI.HtmlControls;
// change the name of the place holder to the one you're using
HtmlTable tbl = this.Master.FindControl("ContentPlaceHolder1").FindControl("camas") as HtmlTable;
Best,
Benny
You need to add runat server like previously stated, but the ID will change based on ListView row. You can add clientidmode="Static" to your table if you expect only 1 table and find using InternamentosListView.FindControl("camas"); otherwise, you will need to add ItemDataBound event.
<asp:ListView ID="InternamentosListView" runat="server" DataSourceID="InternamentosBD" OnItemDataBound="InternamentosListView_ItemDataBound">
<LayoutTemplate>
<table id="camas">
<asp:PlaceHolder runat="server" ID="TablePlaceHolder"></asp:PlaceHolder>
</table>
</LayoutTemplate>
You will need to introduce in code behind
InternamentosListView_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Table tdcamas = (Table)e.Item.FindControl("camas");
}
}

GridView Design : How to add a Blank New Row in GridView after button click

I have GridView with a Button beneath it. Upon clicking the button I want to Add a new blank row just beneath the GridView
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnTest" Text="Test" runat="server" OnClick="btnTest_Click" />
</div>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<strong>Dynamic Grid</strong></td>
</tr>
<tr>
<td>
<asp:GridView ID="GrdDynamic" runat="server" AutoGenerateColumns="true"
OnRowDataBound="GrdDynamic_RowDataBound" >
</asp:GridView>
</td>
</tr>
</table>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</form>
</body>
</html>
and the data is being populated by below way....
In pageLoad I am calling the bind
DataTable dt = GroupBudgetSetUpBLL.Instance.GetAllGroupBudgetSetUp();
GrdDynamic.DataSource = dt;
GrdDynamic.DataBind();
and in rowdatabound I am making the Grid Editable textbox.
protected void GrdDynamic_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int i = 1; i < e.Row.Cells.Count; i++)
{
TextBox txt = new TextBox();
string budget = e.Row.Cells[i].Text.Split('_').LastOrDefault();
string txtID = e.Row.Cells[i].Text.Split('_').FirstOrDefault() + "_" + e.Row.Cells[i].Text.Split('_').Skip(1).FirstOrDefault();
txt.ID = txtID;
txt.Text = budget;
e.Row.Cells[i].Text = "";
e.Row.Cells[i].Controls.Add(txt);
}
}
}
Now upon clicking the "Button" below the Grid I want to display a blank row just beneath the MainGrid , cells control type will be TextBox so that it remains editable.
What I could infer from your question is that you need to add a new blank row beneath the GridView (looking like the last row of the GridView is blank on button_click).
I am not sure how feasible it is to add a new Row to the databound Grid View but instead what you could do is to add a blank row in the data table like below:
Add the below code to your button1_Click():
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = GroupBudgetSetUpBLL.Instance.GetAllGroupBudgetSetUp();
DataRow myRow = dt.NewRow();
dt.Rows.InsertAt(myRow, dt.Rows.Count);
GrdDynamic.DataSource = dt;
GrdDynamic.DataBind();
}

Categories

Resources