Copy a ListView and show it on a new page - c#

I am trying to copy a ListView from one class to another and show that ListView on a new aspx page. What I am doing is I am selecting certain values from the first ListView and only those items will be shown on a new page. However, I can't figure out how to show the ListView on a new page because I am used to using a SqlDataSource. I am passing the ListView through the addList method and I have already created a new ListView in the new aspx file.
Please let me know the best way to handle this and if I need to add more information.
Code in First Class
public void CloneButton_Click(object sender, EventArgs e)
{
String droplist = DropDownList2.SelectedValue;
list = new ListView();
if (String.IsNullOrEmpty(droplist))
{
ScriptManager.RegisterStartupScript(this, GetType(), "error", "alert('Please select a Program Name and Report Period');", true);
return;
}
else
{
if (ListView1.Items.Count == 0)
{
Button1_Click(sender, e);
}
else
{
var selectAllCheckBox = (CheckBox)ListView1.InsertItem.FindControl("CheckBox2");
if (selectAllCheckBox.Checked == true)
{
list = ListView1;
Response.Redirect("~/CloneReport.aspx");
return;
}
for (int i = 0; i < ListView1.Items.Count; i++)
{
CheckBox chk = (CheckBox)ListView1.Items[i].FindControl("CheckBox1");
if (chk.Checked == true)
{
list.Items.Add(ListView1.Items[i]);
}
}
CloneReport rep = new CloneReport();
rep.addList(list);
Response.Redirect("~/CloneReport.aspx");
}
}
}
Code in Second Class
public void addList(ListView list)
{
ListView1 = new ListView();
for (int i = 0; i < list.Items.Count; i++)
{
ListView1.Items.Add(list.Items[i]);
}
ListView1.DataBind();
}
ListView Item Template From Old Page(Page Im transferring from)
<ItemTemplate>
<tr style="background-color: #E0FFFF; color: #333333;">
<td>
<asp:CheckBox ID="CheckBox1" runat="server" />
</td>
<td>
<asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Edit" />
<asp:Button ID="DeleteButton" runat="server" CommandName="Delete" Text="Delete" />
</td>
<td>
<asp:Label ID="FormTitleLabel" runat="server" Text='<%# Eval("FormTitle") %>' />
</td>
<td>
<asp:Label ID="FormSectionLabel" runat="server" Text='<%# Eval("FormSection") %>' />
</td>
<td>
<asp:Label ID="SubSectionLabel" runat="server" Text='<%# Eval("SubSection") %>' />
</td>
<td>
<asp:Label ID="SectionItemLabel" runat="server" Text='<%# Eval("SectionItem") %>' />
</td>
<td>
<asp:Label ID="SortOrder" runat="server" Text='<%# Eval("SortOrder") %>' />
</td>
<td>
<asp:Label ID="SectionSortOrder" runat="server" Text='<%# Eval("SectionSortOrder") %>' />
</td>
<td>
<asp:Label ID="SubSectionSortOrder" runat="server" Text='<%# Eval("SubSectionSortOrder") %>' />
</td>
<td>
<asp:Label ID="RuleDesc" runat="server" Text='<%# Eval("RuleDesc") %>' />
</td>
<td>
<asp:Label ID="ControlType" runat="server" Text='<%# Eval("ControlType") %>' />
</td>
<td>
<asp:Label ID="CrossItem" runat="server" Text='<%# Eval("CrossItem") %>' />
</td>
</tr>
</ItemTemplate>
Triggers for Update Panel
<Triggers>
<asp:AsyncPostBackTrigger ControlID="DropDownList1" />
<asp:AsyncPostBackTrigger ControlID="Button1" />
<asp:AsyncPostBackTrigger ControlID="CloneButton" />
</Triggers>
<ContentTemplate>
<div style="text-align: center;">
<asp:Button ID="CloneButton" runat="server" Text="Clone Report Period" OnClick="CloneButton_Click" />
</div>
<div style="text-align: center; position: absolute; margin-left: auto; margin-right: auto; left: 0; right: 0">
<b>Program Name</b>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" DataSourceID="SqlDataSource2" DataTextField="Program" DataValueField="ProgramID">
</asp:DropDownList>
&nbsp &nbsp
<b>Report Period</b>
<asp:DropDownList ID="DropDownList2" runat="server" DataSourceID="SqlDataSource3" DataTextField="ReportLabel" DataValueField="DataCollectionPeriodID" Height="21px" Width="172px">
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Height="30px" OnClick="Button1_Click" Text="Search" />
</div>

You cannot transfer ListView object between pages, but you can do it with DataTable using Server.Transfer.
First Page:
DataTable dtTable;
public DataTable DataTransferTable
{
get { return dtTable; }
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
lstTransferView = new ListView();
DataView dtView = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
dtTable = new DataTable();
dtTable = dtView.ToTable().Clone();
DataRow dtRow;
foreach (ListViewDataItem lstItem in lstView.Items)
{
if (((CheckBox)lstItem.FindControl("chkBox")).Checked)
{
dtRow = (DataRow)dtView.Table.Rows[lstItem.DataItemIndex];
dtTable.ImportRow(dtRow);
}
}
Server.Transfer("~/SecondPage.aspx");
}
Second Page:
public FirstPageClass ftPage;
DataTable dtNewTable;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
ftPage= (FirstPageClass)Context.Handler;
dtNewTable = (DataTable)ftPage.DataTransferTable;
lstSecondView.DataSource = dtNewTable;
lstSecondView.DataBind();
}

Related

using click event of dynamically created button inside dynamically created accordionpane

I have a method that generates accordionpanes and panels and inside each accordionpane I create a button. This methode I use it in the listviewselectedindexchanged method to create the order object and fillup the body panel
protected void PanelCreator(Order order, List<Panel> pnllist)
{
Panel panelHead = new Panel();
panelHead.ID = "pH" + order.product;
panelHead.CssClass = "cpHeader";
//Add Label inside header panel to display text
Label lblHead = new Label();
lblHead.ID = order.product;
lblHead.Text = order.productName + " €" + order.priceValue;
panelHead.Controls.Add(lblHead);
//Create Body Panel
Panel panelBody = new Panel();
panelBody.ID = "pB" + order.product;
panelBody.CssClass = "cpBody";
AccordionPane ap = new AccordionPane();
foreach (Panel p in pnllist)
{
panelBody.Controls.Add(p);
}
Button btn = new Button();
btn.ID = "btn" + order.product;
btn.Text = "Toevoegen";
btn.Click += new EventHandler(btn_Click);
panelHead.Controls.Add(btn);
ap.ID = "ap" + order.product;
ap.HeaderContainer.Controls.Add(panelHead);
ap.ContentContainer.Controls.Add(panelBody);
accMenu.Panes.Add(ap);
}
I am trying to reach each buttons click event but don't know how to do it.
I have this method as for the click event to test a label inside the updatepanel but not working
protected void btn_Click(object sender, EventArgs e)
{
nameLabel.Text = "testinf";
}
this is my aspx page:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
<asp:Panel ID="Panel1" runat="server"></asp:Panel>
<asp:Label ID="nameLabel" runat="server" Text="aa" />
<div style="overflow-x: auto;">
<asp:ListView ID="ListView1" runat="server" DataKeyNames="main_product_id" DataSourceID="odsMainProduct" OnSelectedIndexChanged="ListView1_SelectedIndexChanged">
<ItemTemplate>
<stackpanel orientation="Horizontal" />
<td>
<asp:LinkButton ID="lnkSelect" runat="server" CommandName="Select" Font-Overline="false" Font-Bold="true" Font-Size="15px" Height="30px" Text='<%# Eval("name") %>' />
<%--<asp:Label ID="nameLabel" runat="server" Text='<%# Eval("name") %>' />--%></td>
</ItemTemplate>
<LayoutTemplate>
<table runat="server">
<tr runat="server">
<td runat="server">
<table id="itemPlaceholderContainer" runat="server" border="0" style="">
<tr runat="server" style="color: white; text-align: left; width: auto">
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</td>
</tr>
<tr runat="server">
<td runat="server" style=""></td>
</tr>
</table>
</LayoutTemplate>
<SelectedItemTemplate>
<td>
<asp:LinkButton ID="lnkSelect0" runat="server" CommandName="Select" Font-Overline="false" Font-Size="20px" ForeColor="red" Height="30px" Text='<%# Eval("name") %>' />
<%--<asp:Label ID="nameLabel" runat="server" Text='<%# Eval("name") %>' />--%></td>
</SelectedItemTemplate>
</asp:ListView>
</div>
<asp:ObjectDataSource ID="odsMainProduct" runat="server" OldValuesParameterFormatString="original_{0}" SelectMethod="GetMainProducts" TypeName="MainProductBLL"></asp:ObjectDataSource>
<asp:Accordion ID="accMenu" runat="server"></asp:Accordion>
</ContentTemplate>
</asp:UpdatePanel>
You need to store your button creation data in ViewState for creating these controls in page-load event, after that button click will be processed correct.
Order class should be marked as Serializable
public Order SelectedOrder
{
get
{
return ViewState["StoredOrder"] == null ? (Order)ViewState["StoredOrder"] : null;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (SelectedOrder != null)
{
PanelCreator(SelectedOrder);
}
}
protected void listviewselectedindexchanged(object sender, System.EventArgs e)
{
// I am not sure how you got order in this event, you should use your version of code, but idea is the same
ViewState["StoredOrder"] = sender as Order;
PanelCreator(SelectedOrder);
}

How to delete a row from GridView without affecting the Database

I am populating a Gridview using a form with the help of AJAX.
I want to add a delete button to each row and whendelet button is clicked that row should be deleted from GridView (not hidden).
Here is my aspx code:
<asp:Content ID="Content2" ContentPlaceHolderID="Nav" runat="server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
<table>
<tr>
<td class="auto-style1">
<asp:Label ID="LabelFirstName" runat="server" Text="First Name"></asp:Label>
</td>
<td>
<asp:TextBox ID="TextBoxFirstName" runat="server" CssClass="auto-style2"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style1">
<asp:Label ID="LabelLastName" runat="server" Text="Last Name"></asp:Label>
</td>
<td>
<asp:TextBox ID="TextBoxLastName" runat="server"></asp:TextBox>
</td>
</tr>
</table>
<br /><br />
<asp:Button ID="ButtonSearch" runat="server" Text="Search" CssClass="auto-style3" Width="93px" OnClick="ButtonSearch_Click" />
<br /><br />
<asp:Label ID="LabelNoRows" runat="server" Text="Sorry, we couldn't find any data with this Name." Visible="false" ForeColor="Red"></asp:Label>
<asp:Panel ID="PanelAbsenceInfo" runat="server" Visible="false">
<table>
<tr>
<td class="auto-style4">
<asp:Label ID="LabelFname" runat="server" Text="First Name:"></asp:Label>
</td>
<td>
<asp:Label ID="LabelGetFirstName" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td class="auto-style4">
<asp:Label ID="LabelLname" runat="server" Text="Last Name"></asp:Label>
</td>
<td>
<asp:Label ID="LabelGetLname" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td class="auto-style4">
<asp:Label ID="LabelEmail" runat="server" Text="Email"></asp:Label>
</td>
<td>
<asp:Label ID="LabelGetEmail" runat="server"></asp:Label>
</td>
</tr>
<asp:UpdatePanel ID="UpdatePanelInfo" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<tr>
<td class="auto-style4">
<asp:Label ID="LabelPersonal" runat="server" Text="Personal Days Approved" ></asp:Label>
</td>
<td>
<asp:Label ID="LabelGetPersonal" runat="server" ></asp:Label>
</td>
</tr>
<tr>
<td class="auto-style4">
<asp:Label ID="LabelOther" runat="server" Text="Other Days Approved"></asp:Label>
</td>
<td>
<asp:Label ID="LabelGetOther" runat="server" ></asp:Label>
</td>
</tr>
<tr>
<td class="auto-style4">
<asp:Label ID="LabelTotalDays" runat="server" Text="Total Days Approved" ></asp:Label>
</td>
<td>
<asp:Label ID="LabelgetTotaldays" runat="server" ></asp:Label>
</td>
</tr>
</table>
<br /><br />
<asp:GridView ID="GridViewViewAllRequests" runat="server" AutoGenerateColumns="False" DataKeyNames="id"
OnRowCommand="GridViewViewAllRequests_RowCommand">
<Columns>
<asp:BoundField DataField="scrap" Visible ="false" />
<asp:BoundField DataField="isApproved" Visible="false" />
<asp:BoundField HeaderText="Date of Absence" DataField="requestedDate" DataFormatString="{0:MM/dd/yyyy}" />
<asp:BoundField HeaderText="Rotation Period" DataField="rotationPeriod" />
<asp:BoundField HeaderText="Reason" DataField="reason" />
<asp:BoundField HeaderText="Days Missed" DataField="daysMissed" />
<asp:BoundField HeaderText="Department" DataField="departmentName" />
<asp:BoundField HeaderText="Course" DataField="courseName" />
<asp:TemplateField HeaderText="Approved/Declined">
<ItemTemplate>
<asp:Label ID="LabelApproveorDecline" runat="server" Text='<%# Eval("isApproved") == null ? "Decision not yet made." : ((bool)Eval("isApproved") ? "Approved" : "Declined") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Scrap/Undo">
<ItemTemplate>
<asp:Button ID="ScrapButton" CommandArgument='<%# Eval("id") %>' runat="server" Text="Scrap" CommandName="Scrap" Visible='<%# !(bool)Eval("scrap") %>' />
<asp:Button ID="UndoButton" CommandArgument='<%# Eval("id") %>' runat="server" Text="Undo" CommandName="Undo" Visible='<%# (bool)Eval("scrap") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
<br /><br />
</asp:Content>
And here is my cs code:
public partial class AbsenceRequestMonitor : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ButtonSearch_Click(object sender, EventArgs e)
{
DoAction();
}
public Boolean ScraptheRequest(int id, bool action)
{
bool success = false;
success = DBOperation.ScrapAbsencedate(id, action);
return success;
}
protected void GridViewViewAllRequests_RowCommand(object sender, GridViewCommandEventArgs e)
{
//Determine the RowIndex of the Row whose Button was clicked.
int id = Convert.ToInt32(e.CommandArgument);
//Get the value of column from the DataKeys using the RowIndex.
// int id = Convert.ToInt32(GridViewViewAllRequests.DataKeys[rowIndex].Values[0]);
if(e.CommandName == "Scrap")
{
ScraptheRequest(id, true);
}
else if(e.CommandName == "Undo")
{
ScraptheRequest(id, false);
}
DoAction();
UpdatePanelInfo.Update();
}
public void DoAction()
{
string firstName = null;
string lastName = null;
firstName = TextBoxFirstName.Text.ToString();
lastName = TextBoxLastName.Text.ToString();
double PdCount = 0;
double OtherCount = 0;
if (firstName != null && lastName != null)
{
//gets student data from the Student Form
List<AbsenceMonitorData> l_studentAbsenceInfo = DBOperation.getStudentAbsenceInfo(firstName, lastName);
AbsenceMonitorData studentAbsenceInfo = l_studentAbsenceInfo.FirstOrDefault();
PdCount += l_studentAbsenceInfo.Where(x => x.reason == "Personal Day").Where(y => y.isApproved == true).Where(z => z.scrap == false).Select(a => a.daysMissed).Sum();
OtherCount += l_studentAbsenceInfo.Where(x => x.reason != "Personal Day").Where(y => y.isApproved == true).Where(z => z.scrap == false).Select(a => a.daysMissed).Sum();
GridViewViewAllRequests.DataSource = l_studentAbsenceInfo;
GridViewViewAllRequests.DataBind();
if (l_studentAbsenceInfo.Count > 0)
{
LabelGetPersonal.Text = PdCount.ToString();
LabelGetOther.Text = OtherCount.ToString();
LabelgetTotaldays.Text = (PdCount + OtherCount).ToString();
LabelGetFirstName.Text = studentAbsenceInfo.firstName.ToString();
LabelGetLname.Text = studentAbsenceInfo.lastname.ToString();
LabelGetEmail.Text = studentAbsenceInfo.studentEmail.ToString();
PanelAbsenceInfo.Visible = true;
LabelNoRows.Visible = false;
}
else
{
LabelNoRows.Visible = true;
}
}
}
}
Right now i was using the Scrap/Undo button which i want to replace it with a Delete button.
Also when i delete the row the count should be affected. (ie. Personal Days Approved, Other Days Approved and Total Days Approved)
The image shows that when i type the name and hit search, GridView is obtained.
I need to be able to delete rows from that gridview.
GridView

HyperLink string formating on a repeater

i need help building a dynamic URL.
I have a working asp:HyperLinkField on a GridView, but you can't use it on a reater. i can only use asp:HyperLink.
This is the working one:
<asp:HyperLinkField Text="Select" DataNavigateUrlFormatString="~/Products/Details?ProductID={0}" DataNavigateUrlFields="ProductID" />
And this the one that doesn't
<asp:HyperLink runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "ProductName") %>' NavigateUrl='~/Products/Details?ProductID=BK100' />
I am using it inside a asp:Repeater. thank you.
Hop it helps
<asp:HyperLink ID="HyperLink1" runat=server NavigateUrl='<%# DataBinder.Eval(Container.DataItem, "YourField", "Desc.aspx?query={0}") %>'> <%# DataBinder.Eval(Container.DataItem, "YourFieldForText") %>' </asp:HyperLink>
If you don't mind using C# code to bind..
.aspx
<h2>Grid View</h2>
<br />
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:HyperLinkField HeaderText="Link" Text="Select"
DataNavigateUrlFormatString="~/Products/Details?ProductID={0}"
DataNavigateUrlFields="ProductID" />
</Columns>
</asp:GridView>
<br />
<br />
<h2>Repeater</h2>
<br />
<asp:Repeater ID="r" runat="server" OnItemDataBound="r_ItemDataBound">
<HeaderTemplate>
<table style="padding: 0px; border-spacing: 0px;">
<tr>
<td style="border: 1px solid #ccc; text-align: center;">
<asp:Label ID="lblTitle" runat="server" Text="Link"
Font-Bold="true"></asp:Label>
</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td style="border: 1px solid #ccc; border-top: 0px;">
<asp:Label ID="lblHidden" runat="server"
Text='<%# Eval("ProductID") %>' Visible="false"></asp:Label>
<asp:HyperLink ID="hl" runat="server"
Text='<%# Eval("ProductName") %>'></asp:HyperLink>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
.cs
protected void Page_Load(object sender, EventArgs e)
{
// Check
if (!IsPostBack)
{
// Variable
string[] productName = { "SharePoint", "CRM", "SiteCore", "Silver Light" };
DataTable dt = new DataTable();
dt.Columns.Add("ProductID");
dt.Columns.Add("ProductName");
for (int i = 0; i < productName.Length; i++)
dt.Rows.Add((i + 1) + "", productName[i]);
// Bind Grid View
gv.DataSource = dt;
gv.DataBind();
// Bind Repeater
r.DataSource = dt;
r.DataBind();
}
}
protected void r_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
// Variable
string url = "/Products/Details?ProductID={0}";
// Find Control
HyperLink hl = e.Item.FindControl("hl") as HyperLink;
Label lblHidden = e.Item.FindControl("lblHidden") as Label;
// Check
if (hl != null && lblHidden != null)
{
// Set Navigation Url
url = string.Format(url, lblHidden.Text.Trim());
hl.NavigateUrl = url;
}
}
}
You can try this
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# "~/Products/Details?ProductID="+Eval("ProductID") %>'> <%# Eval("ProductName") %> </asp:HyperLink>

Literal Control in ASP.NET HTML Table

I have a HTML table like following in my aspx markup file.
<table runat="server" id="tblSubstantialOwners">
<tr id="tr_header" runat="server">
<td>
<asp:Label ID="lblOnwerName" Text="Name" runat="server"></asp:Label>
</td>
<td>
<asp:Label ID="lblOwnerAddress" Text="Address" runat="server"></asp:Label>
</td>
<td>
<asp:Label ID="lblOwnerTIN" Text="TIN" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="txtOwnerName1" Width="80px" runat="server" AutoCompleteType="Disabled"
MaxLength="20" />
</td>
<td>
<asp:TextBox ID="txtOwnerAddress1" Width="80px" runat="server" AutoCompleteType="Disabled"
MaxLength="20" />
</td>
<td>
<asp:TextBox ID="txtOwnerTIN1" Width="80px" runat="server" AutoCompleteType="Disabled"
MaxLength="20" />
</td>
</tr>
</table>
but when I parse through c# asp.net code, I get literal control in each cell of html table row along with my asp.net control i.e. TextBox. Why is that?
foreach (HtmlTableRow row in htmlTable.Rows)
{
if (row.ID != "tr_header")
{
for (int count = 0; count < row.Cells.Count; count++)
{
string value = string.Empty;
HtmlTableCell cell = row.Cells[count];
foreach (Control conrol in cell.Controls)
{
if (conrol.GetType() != typeof(LiteralControl))
{
if (conrol.GetType() != typeof(Label))
{
if (conrol.GetType() == typeof(TextBox))
{
datarow[count] = ((TextBox)conrol).Text;
}
}
}
}
}
}
}
it appears that you are mixing Html Tables and ASP.NET.
If you change your Html Table to:
<asp:Table runat="server" ID="tblSubstantialOwners">
<asp:TableHeaderRow ID="tr_header" runat="server">
<asp:TableHeaderCell>
<asp:Label ID="lblOnwerName" Text="Name" runat="server"></asp:Label>
</asp:TableHeaderCell>
<asp:TableHeaderCell>
<asp:Label ID="lblOwnerAddress" Text="Address" runat="server"></asp:Label>
</asp:TableHeaderCell>
<asp:TableHeaderCell>
<asp:Label ID="lblOwnerTIN" Text="TIN" runat="server"></asp:Label>
</asp:TableHeaderCell>
</asp:TableHeaderRow>
<asp:TableRow>
<asp:TableCell>
<asp:TextBox ID="txtOwnerName1" Width="80px" runat="server" AutoCompleteType="Disabled"
MaxLength="20" />
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtOwnerAddress1" Width="80px" runat="server" AutoCompleteType="Disabled"
MaxLength="20" />
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtOwnerTIN1" Width="80px" runat="server" AutoCompleteType="Disabled"
MaxLength="20" />
</asp:TableCell>
</asp:TableRow>
</asp:Table>
And your code to:
protected void btnSubmit_Click(object sender, EventArgs e)
{
foreach (System.Web.UI.WebControls.TableRow row in tblSubstantialOwners.Rows)
{
if (row.GetType() == typeof(TableRow))
{
for (int count = 0; count < row.Cells.Count; count++)
{
TableCell cell = row.Cells[count];
datarow[count] = cell.Controls.OfType<TextBox>().FirstOrDefault().Text;
}
}
}
}
You can get to the controls you have in your table cells directly, either by name, ordinality, or type...

Best way to show/hide a textbox when checkbox is checked/unchecked in a datalist

I'm new to aspnet programming and need some help. I've been scouring the internet and can't find a solution to my problem. I basically need a way to have a textbox show only when it's corresponding checkbox is checked. The textboxes and checkboxes are part of an inner datalist; the controls have to be databound. I've tried JQuery and couldn't get it to work, so now I'm trying AJAX with the UpdatePanel--still not working right. Below is my current code which resides in a user control. I basically included code that pertains to the checkboxes/textboxes. The script manager is referenced in the master page. Any help would be appreciated.
Thanks in advance!
HTML ----->
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:DataList ID="outerDataList" runat="server" OnItemDataBound="outerRep_ItemDataBound">
<ItemTemplate>
<div id="div1" runat="server" visible='<%# ((string)Eval("Code")) != "BABRB" %>'>
<asp:Label ID="lblBABProdType" Font-Size="Medium" Font-Bold="true" runat="server" Text='<%# Eval("Name") %>' style="padding-left:20px" />
<asp:DataList ID="innerDataList" runat="server" RepeatColumns="3" DataKeyField="ProductID" >
<ItemTemplate>
<div id="div4" runat="server" visible='<%# ((string)Eval("ProductCode")) == "BABBE" %>'>
<table ID="table4" runat="server" align="left" width="80%" style="margin-left:30px; font-size:smaller">
<tr>
<td width="3%">
<asp:CheckBox ID="bevCheckBox" runat="server" AutoPostBack="true"
OnCheckedChanged="chkBox_CheckedChanged"/>
</td>
<td align="left" width="7%">
<asp:ImageButton ID="bevImgBtn" runat="server" width="40" height="40" align="middle"
ImageUrl='<%# "~/ProductImages/"+Eval("Image1FileName").ToString() %>'
OnClick="ImgBtn_Click" CommandArgument='<%# Eval("ProductID") %>'/>
</td>
<td valign="middle" width="70%">
<span class="ProductName">
<asp:LinkButton ID="bevLnkBtn" runat="server" OnClick="LnkBtn_Click" CssClass="BABProductName"
CommandArgument='<%# Eval("ProductID") %>'>
<%# DataBinder.Eval(Container.DataItem, "Name")%>
<br /></asp:LinkButton>
</span>
<span class="ProductPrice">
<%# DataBinder.Eval(Container.DataItem, "Price", "{0:c}")%>
</span
<asp:TextBox ID="bevQtyTxtBox" runat="server" Text="Qty: " Font-Size="XX-Small"
Width="40px" ViewStateMode="Disabled"/>
</td>
</tr>
</table>
</div>
<div id="div5" runat="server" visible='<%# ((string)Eval("ProductCode")) == "BABFO" %>' >
<table ID="table5" runat="server" align="left" width="80%" style="margin-left:30px; font-size:smaller">
<tr>
<td width="3%">
<asp:CheckBox ID="foodCheckBox" runat="server" AutoPostBack="true"
OnCheckedChanged="chkBox_CheckedChanged"/>
</td>
<td align="left" width="7%">
<asp:ImageButton ID="foodImgBtn" runat="server" width="40" height="40" align="middle"
ImageUrl='<%# "~/ProductImages/"+Eval("Image1FileName").ToString() %>'
OnClick="ImgBtn_Click" CommandArgument='<%# Eval("ProductID") %>'/>
</td>
<td valign="middle" width="70%">
<span class="ProductName">
<asp:LinkButton ID="foodLnkBtn" runat="server" OnClick="LnkBtn_Click" CssClass="BABProductName"
CommandArgument='<%# Eval("ProductID") %>'>
<%# DataBinder.Eval(Container.DataItem, "Name")%>
<br /></asp:LinkButton>
</span>
<span class="ProductPrice">
<%# DataBinder.Eval(Container.DataItem, "Price", "{0:c}")%>
</span>
<asp:TextBox ID="foodQtyTxtBox" runat="server" Text="Qty: " Font-Size="XX-Small"
Width="40px" ViewStateMode="Disabled"/>
</td>
</tr>
</table>
</div>
</ItemTemplate>
</asp:DataList>
</div>
<br />
</ItemTemplate>
</asp:DataList>
</ContentTemplate>
</asp:UpdatePanel>
CODE BEHIND ----->
protected void Page_Load(object sender, EventArgs e)
{
PopulateData();
}
private void PopulateData()
{
// Retrieve list of products
string categoryID = Request.QueryString["BABCategoryID"];
// set the stored procedure name
SqlConnection sqlConn = new SqlConnection(ChocolateExpConfiguration.DbConnectionString);
SqlCommand sqlComm = new SqlCommand("GetBABProductsInCategory", sqlConn);
sqlComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adptr = new SqlDataAdapter(sqlComm);
sqlComm.Parameters.AddWithValue("#BABCategoryID", categoryID);
DataSet ds = new DataSet();
adptr.Fill(ds);
ds.Relations.Add(new DataRelation("CodeRelation", ds.Tables[0].Columns["Code"], ds.Tables[1].Columns["ProductCode"]));
outerDataList.DataSource = ds.Tables[0];
outerDataList.DataBind();
}
protected void outerRep_ItemDataBound(object sender, DataListItemEventArgs e)
{
if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
{
DataRowView drv = e.Item.DataItem as DataRowView;
DataList innerDataList = (DataList)e.Item.FindControl("innerDataList");
innerDataList.DataSource = drv.CreateChildView("CodeRelation");
innerDataList.DataBind();
}
}
protected void chkBox_CheckedChanged(object sender, EventArgs e)
{
foreach (DataListItem parentItem in outerDataList.Items)
{
//Find nested items(DataList) of parent Datalist
DataList innerDataList = (DataList)parentItem.FindControl("innerDataList");
foreach (DataListItem childItem in innerDataList.Items)
{
CheckBox bevCheckBox = (CheckBox)childItem.FindControl("bevCheckBox");
CheckBox foodCheckBox = (CheckBox)childItem.FindControl("foodCheckBox");
TextBox bevQtyTxtBox = (TextBox)childItem.FindControl("bevQtyTxtBox");
TextBox foodQtyTxtBox = (TextBox)childItem.FindControl("foodQtyTxtBox");
if ((bevCheckBox.Checked == true) || (foodCheckBox.Checked == true))
{
bevQtyTxtBox.Visible = true;
foodQtyTxtBox.Visible = true;
}
else
{
bevQtyTxtBox.Visible = false;
foodQtyTxtBox.Visible = false;
}
UpdatePanel1.Update();
}
}
}*
protected void EnableTextBox()
{
int count = int.Parse(GridView1.Rows.Count.ToString());
for (int i = 0; i < count; i++)
{
CheckBox cb = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBox1");
CheckBox cb1 = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBox2");
CheckBox cb2 = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBox3");
TextBox tb = (TextBox)GridView1.Rows[i].Cells[4].FindControl("txtration");
TextBox tb1 = (TextBox)GridView1.Rows[i].Cells[5].FindControl("txtjob");
TextBox tb2 = (TextBox)GridView1.Rows[i].Cells[6].FindControl("txtaadhar");
if (cb.Checked == true)
{
tb.Visible = true;
}
else
{
tb.Visible = false;
}
if (cb1.Checked == true)
{
tb1.Visible = true;
}
else
{
tb1.Visible = false;
}
if (cb2.Checked == true)
{
tb2.Visible = true;
}
else
{
tb2.Visible = false;
}
}
}
in checkedchanged event
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
EnableTextBox();
}

Categories