asp:c# Print checked rows using checkbox - c#

i want to print the selected rows in a repeater table when a button clicked, this is the .aspx code:
<asp:Repeater ID="rptItems" runat="server">
<HeaderTemplate>
<table class="table table-bordered table-hover table-responsive table-striped table-condensed">
<tr>
<th> </th>
<th>Goods Desc</th>
<th>Balance Units</th>
<th>Exit Units</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><asp:CheckBox ID="cbItem" runat="server" ClientIDMode="AutoID" AutoPostBack="True" /></td>
<td><asp:Label runat="server" Id="lblCampCode" Text='<%#Eval("ItemDesc") %>'></asp:Label></td>
<td><asp:Label ID="lblBalUnits" runat="server" text='<%#Eval("InvoicBalanceUnits") %>'></asp:Label> </td>
<td><asp:TextBox ID="txtExitUnits" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="revUnits" runat="server" Display="Dynamic" ControlToValidate="txtExitUnits" ValidationExpression="^\d+$" ErrorMessage="Please, insert a number." CssClass="text-danger"></asp:RegularExpressionValidator>
<asp:RequiredFieldValidator ID="rfvUnits" runat="server" Display="Dynamic" ControlToValidate="txtExitUnits" ErrorMessage="Insert number of units." CssClass="text-danger"></asp:RequiredFieldValidator>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
<asp:Button ID="btnExit" runat="server" Text="Exit now" OnClick="btnExit_Click" />
and this is the .cs code for button click event which will loop for ever checked item in the repeater, and will retrieve the checked rows data:
protected void btnExit_Click(object sender, EventArgs e)
{
foreach (RepeaterItem item in rptItems.Items)
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
CheckBox checkBoxInRepeater = item.FindControl("cbItem") as CheckBox;
if (checkBoxInRepeater.Checked)
{
Label lblCampCode = (Label)item.FindControl("lblCampCode");
Label lblBalUnits = (Label)item.FindControl("lblBalUnits");
TextBox txtExitUnits = (TextBox)item.FindControl("txtExitUnits");
string CampCode = lblCampCode.Text;
string BalUnits = lblBalUnits.Text;
string ExitUni = txtExitUnits.Text;
}
}
}
}
i think that i should use datatable to store the data.

I solve it by using Datatable like this:
DataTable checkedData = new DataTable();
checkedData.Columns.AddRange(new DataColumn[6] { new DataColumn("CampCode"), new DataColumn("BalUnits", typeof(decimal)), new DataColumn("ExitUni",typeof(decimal)), new DataColumn("itemNum"), new DataColumn("UOM"), new DataColumn("WT", typeof(decimal)) });
dr["CampCode"]=lblexitUnits.text;
//And so on
DataRow dr = checkedData.NewRow();

Related

Conditional Formatting of asp:Label based on database value

I have labels in a ListView that display the size and finish of an object (an SKU). I would like to change the color of the font of those labels if that particular SKU is "in stock" (has a stockedid of 1). The stocked attribute is part of the table with the size and finish, but it is not displayed. I have looked for a solution, but nothing seems to be exactly what I want, since I am not displaying the information that is used to format the label.
Please "speak slowly" :-) as I'm a relative novice with this type of thing. (As is probably evident.)
<asp:ListView ID="ListViewSSD" runat="server" DataSourceID="SSD" >
<ItemTemplate>
<div id="sdoptions">
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# Eval("SKU", "ST.aspx?SKU={0}") %>' ImageUrl='<%# Eval("image1path", "Images/{0}") %>' ></asp:HyperLink>
<asp:Label ID="Label8" runat="server" Text='<%# Eval("length", "{0}\" x ") %>'></asp:Label>
<asp:Label ID="Label9" runat="server" Text='<%# Eval("width", "{0}\"") %>'></asp:Label>
<asp:Label ID="finishLabel" runat="server" cssClass="tinyprint" Text='<%# Eval("finish", "({0})") %>' />
</div>
</ItemTemplate>
</asp:ListView>
Thank you.
The "spot" or party room for formatting is in general the row data bind event.
This event lets you get your hands on each row, and do formatting.
so, for a repeater, listview, gridview etc.?
row data bind.
And note that "during" the data bind process, the full database row that you feed the data aware object (listview, gridview etc.) is avaible.
So, say I full out a listview with list of hotels, but for "active" hotels, I want say to highlight in blue. While the column "active" is in the data source, it not on the listview.
So then say this:
<asp:ListView ID="MyHotels" runat="server" DataKeyNames="ID"
OnItemDataBound="MyHotels_ItemDataBound" >
<ItemTemplate>
<tr style="">
<td><asp:Label ID="FirstNameLabel" runat="server" Text='<%# Eval("FirstName")%>' /> </td>
<td><asp:Label ID="LastNameLabel" runat="server" Text='<%# Eval("LastName") %>' /></td>
<td runat="server"><asp:Label ID="HotelNameLabel" runat="server" Text='<%# Eval("HotelName") %>' /></td>
<td><asp:Label ID="CityLabel" runat="server" Text='<%# Eval("City") %>' /></td>
<td style="width:350px">
<asp:Label ID="DescriptionLabel" runat="server" Text='<%# Eval("Description") %>' />
</td>
<td style="text-align:center;vertical-align:middle">
<asp:Button ID="cmdView" runat="server" Text="View" class="btn"/>
</td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<table id="itemPlaceholderContainer" runat="server"
class="table table-bordered table-hover">
<tr runat="server" style="">
<th runat="server">FirstName</th>
<th runat="server">LastName</th>
<th runat="server">HotelName</th>
<th runat="server">City</th>
<th runat="server">Description</th>
<th runat="server" style="text-align:center">View Hotel</th>
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</LayoutTemplate>
</asp:ListView>
My code to fill:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadData();
}
void LoadData()
{
string strSQL = #"SELECT * FROM tblHotelsA ORDER BY HotelName";
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
cmdSQL.Connection.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
MyHotels.DataSource = rstData;
MyHotels.DataBind();
}
And we get/see this:
We set the font bold (for any active hotel).
We set font italic, and also background of the cell to blue.
That code was this:
protected void MyHotels_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
DataRowView gData = e.Item.DataItem as DataRowView;
if ((bool)gData["Active"])
{
Label lblHotel = e.Item.FindControl("HotelNameLabel") as Label;
lblHotel.Font.Bold = true;
lblHotel.Font.Italic = true;
// get holdring cell
HtmlTableCell mycell = lblHotel.Parent as HtmlTableCell;
mycell.BgColor = "skyblue";
}
}
}
Based on Albert Kallal's answer, I was able to find another article that helped me to find an easy-for-me solution.
protected void ListViewSSD_ItemDataBound(object sender, ListViewItemEventArgs e)
{
Label Label8;
if (e.Item.ItemType == ListViewItemType.DataItem)
{
Label8 = (Label)e.Item.FindControl("Label8");
System.Data.DataRowView rowView = e.Item.DataItem as System.Data.DataRowView;
string stockstatus = rowView["stockedid"].ToString();
if (stockstatus == "1")
{
Label8.Font.Bold = true;
Label8.CssClass = "greenitalic";
}
}
Label Label9;
if (e.Item.ItemType == ListViewItemType.DataItem)
{
Label9 = (Label)e.Item.FindControl("Label9");
System.Data.DataRowView rowView = e.Item.DataItem as System.Data.DataRowView;
string stockstatus = rowView["stockedid"].ToString();
if (stockstatus == "1")
{
Label9.Font.Bold = true;
Label9.CssClass = "greenitalic";
}
}
}

Highlight ListView row without re-bind or apply style to that row

Typical listview.
<asp:ListView ID="ListView1" runat="server" DataKeyNames="ID" OnSelectedIndexChanging="ListView1_SelectedIndexChanging"
OnSelectedIndexChanged="ListView1_SelectedIndexChanged">
<ItemTemplate>
<tr style="">
<td>
<asp:Label ID="FirstNameLabel" runat="server" Text='<%# Eval("FirstName") %>' />
</td>
<td>
<asp:Label ID="LastNameLabel" runat="server" Text='<%# Eval("LastName") %>' />
</td>
<td>
<asp:Label ID="HotelNameLabel" runat="server" Text='<%# Eval("HotelName") %>' />
</td>
<td>
<asp:Label ID="CityLabel" runat="server" Text='<%# Eval("City") %>' />
</td>
<td>
<asp:Button ID="cmdLstSel" runat="server" Text="View" CssClass="btn"
CommandName="Select"/>
</td>
</tr>
</ItemTemplate>
<SelectedItemTemplate>
<tr style="" class="alert-info">
<td>
<asp:Label ID="FirstNameLabel" runat="server" Text='<%# Eval("FirstName") %>' />
</td>
<td>
<asp:Label ID="LastNameLabel" runat="server" Text='<%# Eval("LastName") %>' />
</td>
<td>
<asp:Label ID="HotelNameLabel" runat="server" Text='<%# Eval("HotelName") %>' />
</td>
<td>
<asp:Label ID="CityLabel" runat="server" Text='<%# Eval("City") %>' />
</td>
<td>
<asp:Button ID="cmdLstSel" runat="server" Text="View" CssClass="btn" OnClick="cmdLstSel_Click" />
</td>
</tr>
</SelectedItemTemplate>
<LayoutTemplate>
<table runat="server">
<tr runat="server">
<td runat="server">
<table id="itemPlaceholderContainer" runat="server" border="0" style="">
<tr runat="server" style="">
<th runat="server">FirstName</th>
<th runat="server">LastName</th>
<th runat="server">HotelName</th>
<th runat="server">City</th>
<th runat="server">View</th>
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</td>
</tr>
<tr runat="server">
<td runat="server" style="">
<asp:DataPager ID="DataPager1" runat="server">
<Fields>
<asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True" ShowLastPageButton="True" />
</Fields>
</asp:DataPager>
</td>
</tr>
</table>
</LayoutTemplate>
</asp:ListView>
So we can highlight the row clicked with:
protected void ListView1_SelectedIndexChanging(object sender, ListViewSelectEventArgs e)
{
}
protected void ListView1_SelectedIndexChanged(object sender, EventArgs e)
{
GPayments.DataSource = MyRst("SELECT * FROM HotelPayments WHERE Hotel_ID = " + hID);
GPayments.DataBind();
}
Now if I leave out the re-bind, then of course the row will highlight, but of course it is the "previous" row that hight lights.
And if I could set the class of the ONE row, then I could dump the selected item template.
You can do this with GREAT ease in a GridView, and I often do this:
Dim gRow As GridViewRow = -- get any row
gRow.CssClass = " alert-info"
however, I would like to do the same with listView. When I do above for GridView, then I don't need or have to bother with a re-bind, and I don't even need a selected template either.
So left is a grid view, and we get this:
However, I want to do this with listview.
(and WITHOUT having to do a re-bind).
Any simple way to highlight a row in ListView WITHOUT a re-bind?
Ok, a bit of googling, and the solution becomes VERY easy.
The goal here is to click on a row - highlight that row.
Of course WAY too much work to have to include a selected row template.
It is a better trade off to add 3 lines of code to do this.
So, say we have this markup:
<asp:ListView ID="ListView1" runat="server" DataKeyNames="ID"
OnSelectedIndexChanged="ListView1_SelectedIndexChanged" OnSelectedIndexChanging="ListView1_SelectedIndexChanging" >
<ItemTemplate>
<tr id="mytr" runat="server">
<td><asp:Label ID="FirstNameLabel" runat="server" Text='<%# Eval("FirstName") %>' /></td>
<td><asp:Label ID="LastNameLabel" runat="server" Text='<%# Eval("LastName") %>' /></td>
<td><asp:Label ID="HotelNameLabel" runat="server" Text='<%# Eval("HotelName") %>' /></td>
<td><asp:Label ID="CityLabel" runat="server" Text='<%# Eval("City") %>' /></td>
<td>
<asp:Button ID="cmdLstSel" runat="server" Text="View" CssClass="btn"
CommandName="Select" OnClick="cmdLstSel_Click"/>
</td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<table id="itemPlaceholderContainer" runat="server" border="0" class="table table-hover" style="">
<tr runat="server" style="">
<th runat="server">FirstName</th>
<th runat="server">LastName</th>
<th runat="server">HotelName</th>
<th runat="server">City</th>
<th runat="server">View</th>
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</LayoutTemplate>
</asp:ListView>
ok, our code to fill is this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadView();
}
}
void LoadView()
{
ListView1.DataSource = MyRst("SELECT TOP 12 * FROM tblHotels ORDER BY HotelName");
ListView1.DataBind();
}
Output:
Ok, so for the row click? Well, we don't have to use the selected index changed, but, for this we will (so CommandName="Select" is what triggers that index changed event).
However, I want a simple button click, and with some code (to display the details part).
So, our button click is this:
protected void cmdLstSel_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
ListViewDataItem gRow = (ListViewDataItem)btn.Parent.Parent.Parent;
int hID = (int)ListView1.DataKeys[gRow.DisplayIndex]["ID"];
GHotelOptions.DataSource = MyRst("SELECT * FROM HotelOptions WHERE Hotel_ID = " + hID);
GHotelOptions.DataBind();
GPayments.DataSource = MyRst("SELECT * FROM HotelPayments WHERE Hotel_ID = " + hID);
GPayments.DataBind();
}
Above will fill the child tables. Note the cool trick to get the row - I don't bother with the listview event model!
Now for the row highlight.
The trick is to add an "id" to the tr row like this:
<ItemTemplate>
<tr id="mytr" runat="server">
So, we can now pick up the tr element.
So on lv index changed, we do this:
protected void ListView1_SelectedIndexChanged(object sender, EventArgs e)
{
ListViewItem gRow = (ListViewItem)ListView1.Items[ListView1.SelectedIndex];
if ( (ViewState["MySel"] != null) && ((int)ViewState["MySel"] != gRow.DataItemIndex) )
{
ListViewItem gLast = ListView1.Items[(int)ViewState["MySel"]];
HtmlTableRow hTRL = (HtmlTableRow)gLast.FindControl("mytr");
hTRL.Attributes.Add("class", "");
}
HtmlTableRow hTR = (HtmlTableRow)gRow.FindControl("mytr");
hTR.Attributes.Add("class", "alert-info");
ViewState["MySel"] = gRow.DataItemIndex;
}
So, I did use row state, but that lets me un-highlight + highlight, and I do NOT hve to re-bind the grid.
And I just picked a nice boot strap class - it even "reverses" the text - very nice.
So now we get this:
So this did cost about 4-5 extra lines. But, we trade that for NOT having a selected template in the lv (and that's too much to maintain both the row layout and THEN have to maintains the same for selected template. And worse, you STILL had to re-bind for the highlighted row click to show. This way, we don't.
I also used a "helper" routine to get a datatable, and that was this:
public DataTable MyRst(string strSQL)
{
DataTable rstData = new DataTable();
using (SqlCommand cmdSQL = new SqlCommand(strSQL,
new SqlConnection(Properties.Settings.Default.TEST3)))
{
cmdSQL.Connection.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
return rstData;
}
At the end of the day, we can now highlight the row, do so with a click, and we could even move the selected index changed code to our button code and not even use the lv index and built in events.

hide column in an asp.net listview?

I have below list view , how can i hide column by code behind ?
<asp:ListView ID="AuditLogListView" runat="server" OnItemCreated="AuditLogListView_ItemCreated">
<LayoutTemplate>
<table class="table table-striped table-bordered small">
<tr class="table-secondary">
<th id="BlockHeader" runat="server" style="white-space: normal;">
<asp:Literal ID="BlockHeaderLiteral" runat="server" Text="<%$ Resources:AppResources, AuditInformationBlockHeader %>" />
</th>
</tr>
<asp:PlaceHolder runat="server" ID="ItemPlaceholder"></asp:PlaceHolder>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td id="BlockStatus" runat="server">
<%# Eval("BlockStatus")%>
</td>
</tr>
</ItemTemplate>
After binding data with list view i tried below code behind but with this header text only hide but column still can still visible
if (groupOrBlockValue == 'W')
{
AuditLogListView.FindControl("BlockHeader").Visible = false;
AuditLogListView.FindControl("BlockHeaderLiteral").Visible = false;
//AuditLogListView.FindControl("BlockStatus").Visible = false;
}
Missing part of the list view?
With this:
<asp:ListView ID="LstMarks" runat="server" DataKeyNames="ID" >
<ItemTemplate>
<tr style="">
<td><asp:Textbox ID="Course" runat="server" Text='<%# Eval("Course") %>' /></td>
<td><asp:Textbox ID="Mark" runat="server" Text='<%# Eval("Mark") %>' Width="30px"/></td>
<td>
<asp:CheckBox ID="DoneLabs" runat="server" Checked = '<%# Eval("DoneLabs") %>' Width="30px"/>
</td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<table id="itemPlaceholderContainer" runat="server" border="0" class="table">
<tr runat="server" style="">
<th runat="server" >Course</th>
<th runat="server">Mark</th>
<th id= "LabW" runat="server" >Completed Lab Work</th>
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</LayoutTemplate>
</asp:ListView>
<br />
<br />
<asp:Button ID="cmdHide" runat="server" Text="Hide Lab check box" OnClick="cmdHide_Click" />
So note in the layout, we added a "id" = LabW - that lets you hide the header.
so, a simple button that would toggle (hide/show) the lvColum, then this works:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * from StudentCourses",
new SqlConnection(Properties.Settings.Default.TEST4)))
{
cmdSQL.Connection.Open();
LstMarks.DataSource = cmdSQL.ExecuteReader();
LstMarks.DataBind();
}
}
}
protected void cmdHide_Click(object sender, EventArgs e)
{
Control ctrHeader = LstMarks.FindControl("LabW");
ctrHeader.Visible = !ctrHeader.Visible;
foreach (ListViewItem lvRow in LstMarks.Items)
{
CheckBox ckBox = (CheckBox)lvRow.FindControl("DoneLabs");
ckBox.Visible = !ckBox.Visible;
}
}
So, we get this:
And clicking on the button, we get this:
And both the values changed - they persist - even when you click again (to toggle and show the hidden columns).
Edit: =====================================================
So, say this markup:
<asp:ListView ID="AuditLogListView" runat="server"
OnItemCreated="AuditLogListView_ItemCreated">
<LayoutTemplate>
<table class="table table-striped table-bordered small">
<tr class="table-secondary">
<th id="BlockHeader" runat="server" style="white-space: normal;">
<asp:Literal ID="BlockHeaderLiteral" runat="server" Text="Hotel Name" />
</th>
</tr>
<asp:PlaceHolder runat="server" ID="ItemPlaceholder"></asp:PlaceHolder>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td id="BlockStatus" runat="server">
<%# Eval("BlockStatus")%>
</td>
</tr>
</ItemTemplate>
</asp:ListView>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
And code behind button to hide is this:
protected void Button1_Click(object sender, EventArgs e)
{
Control ctrHeader = AuditLogListView.FindControl("BlockHeaderLiteral");
ctrHeader.Visible = !ctrHeader.Visible;
foreach (ListViewItem lvRow in AuditLogListView.Items)
{
Control BlockStat = (Control)lvRow.FindControl("BlockStatus");
BlockStat.Visible = !BlockStat.Visible;
}
}
At which event have you written this code?
Required this code in the OnDataBound event. And in your code this event missing.
<asp:ListView ID="AuditLogListView" runat="server" OnItemCreated="AuditLogListView_ItemCreated" OnDataBound="AuditLogListView_DataBound">
<asp:Literal ID="BlockHeaderLiteral" runat="server" Text="<%$ Resources:AppResources, AuditInformationBlockHeader %>" /><asp:PlaceHolder runat="server" ID="ItemPlaceholder"></asp:PlaceHolder>
C# Code:
protected void AuditLogListView_DataBound(object sender, EventArgs e)
{AuditLogListView.FindControl("BlockHeaderLiteral").Visible = false;}

Is there a way to select a row from a child repeater and insert it into a parent repeater row/fields in ASP.NET C#?

Ok, so I have this challenge and I'm still learning how things work in ASP C#. I have a parent update panel and inside that is a parent repeater. Inside that is a child update panel (not sure how necessary that is) and a child repeater. The Child repeater is for search results. When the user clicks on the textbox for entry of the parent repeater, an Ajax pop up occurs that allows them to search for the person they need in our LDAP AD system in the child updatepanel and when they enter a Last Name, First Name (or both) or an email and click "Search", the code behind does it's work, finds the results, populates the repeater and gets databound. I have this all happening in the parent OnItemCommand and it works. Here's my challenge - how in the world to I take the child row selected via button onclick and insert the data into the parent row items?
Here's my aspx code section, I apologize for the formatting:
<table class="project_info">
<tr>
<td colspan="3">
<dl>
<dt>Project Stakeholders<br />
<asp:Label runat="server" ID="sh_SHHeader" Text="Stakeholder" Width="314"></asp:Label>
<asp:Label runat="server" ID="sh_SHInput" Text="Input Level" Width="168"></asp:Label>
</dt>
<asp:UpdatePanel runat="server" ID="udp_SubProjectsTeamList" UpdateMode="Conditional">
<ContentTemplate>
<asp:Repeater ID="AddStakeholder" runat="server" OnItemCommand="AddStakeholder_ItemCommand" OnItemDataBound="AddStakeholder_ItemDataBound">
<ItemTemplate>
<dd>
<asp:HiddenField ID="hdn_StakeholderId" runat="server" />
<asp:HiddenField ID="hdn_StakeholderGUID" runat="server" />
<asp:TextBox ID="txt_Stakeholder" runat="server" Width="304" onkeyup="hasPendingChanges()" placeholder="Last Name, First Name" Text='<%# DataBinder.Eval(Container.DataItem, "MSStakeholder") %>'></asp:TextBox>
<ajax:ModalPopupExtender runat="server" ID="aj_AddStakeholder" PopupControlID="pnl_AddStakeholderChild" TargetControlID="txt_Stakeholder" CancelControlID="PopCancelButton" DropShadow="true" Y="50"></ajax:ModalPopupExtender>
<asp:DropDownList ID="drp_SHInput" runat="server" AppendDataBoundItems="true" SelectedIndex='<%# Convert.ToInt32(DataBinder.Eval(Container.DataItem,"MSInput")) %>' Width="160" onchange="hasPendingChanges()">
<asp:ListItem Text="Select Input Level" Value="0" />
</asp:DropDownList>
<asp:Button ID="btnAddAnother" runat="server" CssClass="k-button k-button-icontext repeaterbutton" Font-Size="small" Text='<%# DataBinder.Eval(Container.DataItem, "Button") %>' CommandName='<%# DataBinder.Eval(Container.DataItem, "Button") %>' CausesValidation="false" UseSubmitBehavior="false"/>
<asp:Button ID="btnReset" runat="server" CssClass="k-button k-button-icontext repeaterbutton" Font-Size="small" Font-Bold="false" Text='Reset' ToolTip="Reset Entry" OnClick="clearSHRow" CausesValidation="false" UseSubmitBehavior="false"/>
<asp:Panel ID="pnl_AddStakeholderChild" runat="server" >
<div id="mainformdiv" class="k-widget k-window shPopup">
<div class="k-window-titlebar k-header">
<span class="k-window-title">Stakeholder Search<asp:Button ID="PopCancelButton" runat="server" CssClass="k-button k-button-icontext" Font-Size="small" CausesValidation="false" Text="X" style="float:right;" OnClientClick="this.form.reset();"/></span>
</div>
<div class="k-popup-edit-form k-window-content k-content shPopupHead">
<asp:UpdatePanel runat="server" ID="udp_StakeholderSearch">
<ContentTemplate>
<div style="text-align:center;">
<asp:Label ID="lbl_LastName" runat="server" CssClass="shLabel" Text="Last Name:"/><asp:TextBox ID="txt_LastName" runat="server" Width="200"/> <asp:Label ID="lbl_FirstName" runat="server" CssClass="shLabel" Text="First Name:"/><asp:TextBox ID="txt_FirstName" runat="server" Width="150"/> OR<asp:Label ID="lbl_Email" runat="server" CssClass="shLabel" Text="Email:"/><asp:TextBox ID="txt_Email" runat="server" Width="200"/>
<asp:Button ID="btn_Search" runat="server" CssClass="k-button k-button-icontext" Text="Search" CausesValidation="false" CommandName="Search"></asp:Button>
</div>
<asp:Repeater ID="rpt_SHSearchResults" runat="server">
<HeaderTemplate>
<div class="shPopupResults k-grid k-widget">
<table>
<thead class="k-grid-header">
<tr>
<th class="k-header" rowspan="1">Stakeholder Name</th>
<th class="k-header" rowspan="1">Title</th>
<th class="k-header" rowspan="1">Organization</th>
<th class="k-header" rowspan="1">Email</th>
<th class="k-header" rowspan="1"></th>
</tr>
</thead>
<tbody>
</HeaderTemplate>
<ItemTemplate>
<asp:HiddenField ID="samaccountname" runat="server" Value='<%# Eval("userName") %>'/>
<asp:HiddenField ID="objectGUID" runat="server" Value='<%# Eval("userGUID") %>'/>
<tr class="k-alt">
<td><asp:Label runat="server" ID="name" Text='<%# Eval("FullName") %>' /></td>
<td><asp:Label runat="server" ID="title" Text='<%# Eval("Title") %>' /></td>
<td><asp:Label runat="server" ID="company" Text='<%# Eval("Company") %>' /></td>
<td><asp:Label runat="server" ID="email" Text='<%# Eval("Email") %>' /></td>
<td style="text-align: center;width:auto"><asp:Button runat="server" ID="btn_SHSelect" CssClass="k-button k-button-icontext" Text="Select" CausesValidation="false" UseSubmitBehavior="false"/></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</tbody>
</table>
</div>
</FooterTemplate>
</asp:Repeater>
<asp:Panel ID="pnl_EmptyList" runat="server" Visible="false">
<div class="shEmptyResults k-grid k-widget">
<table>
<tr class="k-alt">
<td colspan="5">
<asp:Label ID="lbl_EmptyList" runat="server" BorderWidth="0"></asp:Label>
</td>
</tr>
</table>
</div>
</asp:Panel>
<asp:Panel ID="pnl_Results" runat="server" Visible="false">
<div class="shPopupHead">
<span class="k-window-title"><asp:Label runat="server" ID="resultCount" style="float:left;" /></span>
</div>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgress ID="udp_SearchProgress" runat="server" AssociatedUpdatePanelID="udp_StakeholderSearch">
<ProgressTemplate>
<div class="shEmptyResults k-grid k-widget">
<table>
<tr class="k-alt">
<td colspan="5" style="background:#fff"><img src="env/images/searching.gif" />
</td>
</tr>
</table>
</div>
</ProgressTemplate>
</asp:UpdateProgress>
</div>
</div>
</asp:Panel>
</dd>
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
</dl>
</td>
</tr>
</table>
And the .cs code behind:
protected void AddStakeholder_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "Search")
{
string last_name = ((TextBox)e.Item.FindControl("txt_LastName")).Text;
string first_name = ((TextBox)e.Item.FindControl("txt_FirstName")).Text;
string email = ((TextBox)e.Item.FindControl("txt_Email")).Text;
TextBox test = ((TextBox)e.Item.FindControl("txt_Email"));
string searchFilter = "";
if (!string.IsNullOrWhiteSpace(last_name) && string.IsNullOrWhiteSpace(first_name) && string.IsNullOrWhiteSpace(email))
{
searchFilter = "(&(objectCategory=person)(objectClass=user)(company=*)(sn=" + last_name + ")(!(UserAccountControl:1.2.840.113556.1.4.803:=2)))";
}
else if (!string.IsNullOrWhiteSpace(last_name) && !string.IsNullOrWhiteSpace(first_name) && string.IsNullOrWhiteSpace(email))
{
searchFilter = "(&(objectCategory=person)(objectClass=user)(company=*)(sn=" + last_name + ")(givenName=" + first_name + ")(!(UserAccountControl:1.2.840.113556.1.4.803:=2)))";
}
else if (!string.IsNullOrWhiteSpace(email))
{
searchFilter = "(&(objectCategory=person)(objectClass=user)(company=*)(userPrincipalName=" + email + ")(!(UserAccountControl:1.2.840.113556.1.4.803:=2)))";
}
//output.Text = "(&(objectCategory=person)(objectClass=user)" + searchFilter + ")";
DirectoryEntry domain = new DirectoryEntry("my company's LDAP server information");
DirectorySearcher dsLookFor = new DirectorySearcher(domain)
{
SearchScope = SearchScope.Subtree,
Filter = searchFilter
};
//dsLookFor.Filter = searchFilter;
dsLookFor.PropertiesToLoad.Add("sAMAccountName");
dsLookFor.PropertiesToLoad.Add("objectGUID");
dsLookFor.PropertiesToLoad.Add("name");
dsLookFor.PropertiesToLoad.Add("title");
dsLookFor.PropertiesToLoad.Add("company");
dsLookFor.PropertiesToLoad.Add("userPrincipalName");
dsLookFor.Sort.Direction = System.DirectoryServices.SortDirection.Ascending;
dsLookFor.Sort.PropertyName = "name";
SearchResultCollection result = dsLookFor.FindAll();
int totalCount = result.Count;
var users = result.Cast<SearchResult>().Select(sr => sr.GetDirectoryEntry()).Select(de => new
{
userName = de.Properties["sAMAccountName"].Value != null ? protectSpecialChar((string)de.Properties["sAMAccountName"].Value) : "",
userGUID = de.Properties["objectGUID"].Value != null ? new Guid((byte[])de.Properties["objectGUID"].Value).ToString() : "",
FullName = de.Properties["name"].Value != null ? protectSpecialChar((string)de.Properties["name"].Value) : "",
Title = de.Properties["title"].Value != null ? protectSpecialChar((string)de.Properties["title"].Value) : "",
Company = de.Properties["company"].Value != null ? protectSpecialChar((string)de.Properties["company"].Value) : "",
Email = de.Properties["userPrincipalName"].Value != null ? protectSpecialChar((string)de.Properties["userPrincipalName"].Value) : "",
}).ToList();
if (totalCount == 0)
{
((Panel)e.Item.FindControl("pnl_EmptyList")).Visible = true;
((Label)e.Item.FindControl("lbl_EmptyList")).Text = "No results to display. Please check your entries and try again.";
}
else
{
rpt_SHSearchResults.DataSource = users;
rpt_SHSearchResults.DataBind();
rpt_SHSearchResults.Visible = true;
((Panel)e.Item.FindControl("pnl_Results")).Visible = true;
((Label)e.Item.FindControl("resultCount")).Text = "Result count: " + totalCount;
}
}
}
protected void AddStakeholder_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
HiddenField hdn_StakeholderId = e.Item.FindControl("hdn_StakeholderId") as HiddenField;
HiddenField hdn_StakeholderGUID = e.Item.FindControl("hdn_StakeholderGUID") as HiddenField;
TextBox txt_Stakeholder = e.Item.FindControl("txt_Stakeholder") as TextBox;
DropDownList drp_SHInput = e.Item.FindControl("drp_SHInput") as DropDownList;
DataSet shInputSet = new DataSet();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["webconfig entry"].ConnectionString))
{
con.Open();
//Contractor List dropdown
SqlDataAdapter shInput = new SqlDataAdapter("SELECT StakeholderInputId,InputName FROM StakeholderInput", con);
shInput.Fill(shInputSet);
drp_SHInput.DataSource = shInputSet;
drp_SHInput.DataTextField = "InputName";
drp_SHInput.DataValueField = "StakeholderInputId";
drp_SHInput.DataBind();
con.Close();
}
Repeater shSearchResults = e.Item.FindControl("rpt_SHSearchResults") as Repeater;
HiddenField userName = shSearchResults.FindControl("samaccountname") as HiddenField;
HiddenField userGUID = shSearchResults.FindControl("objectGUID") as HiddenField;
Label name = shSearchResults.FindControl("name") as Label;
Label title = shSearchResults.FindControl("title") as Label;
Label company = shSearchResults.FindControl("company") as Label;
Label email = shSearchResults.FindControl("email") as Label;
}
}
Should I have a OnClick="dosomethinghere" on the child repeater button "Select" and then take the child row information and attempt to inject it into the parent controls? How would that be accomplished?
I've tried everything I can think of to make this work, and I've done countless searches in Google and SO and elsewhere to see if anyone else has solved this issue. I'm about an intermediate level coder and this one has me stumped. How do I get the selected result row from the child repeater into the parent row?
Thank you for the help!

Auto add row in table HTML

I have an table in my page that lists User and Email when user sends this information
How I can make this table add an row for each post and not delete other line?
My aspx
<table id="tblUsers" class="table table-bordered table-striped">
<tbody id="tbodyUser">
<tr>
<asp:Label ID="lblHeader" Font-Bold="true" runat="server" Visible="false">User to Access</asp:Label>
<td>
<asp:Label ID="lblUser" runat="server" Visible="false"></asp:Label>
</td>
<td>
<asp:Label ID="lblEmail" runat="server" Visible="false"></asp:Label>
</td>
</tr>
</tbody>
</table>
My .cs
protected void btnSendUser_OnClick(object sender, EventArgs e)
{
string LoginInfo = txtUserAdd.Text;
PrincipalContext insPrincipalContext = new PrincipalContext(ContextType.Domain, "x.com", "amsndrsecuritysqlser", "xxx");
UserPrincipal insUserPrincipal = UserPrincipal.FindByIdentity(insPrincipalContext, LoginInfo);
//it's to first post
if (lblUser.Visible == false && lblEmail.Visible == false)
{
if (insUserPrincipal == null)
{
lblError.Visible = true;
}
else
{
lblUser.Visible = true;
lblEmail.Visible = true;
lblHeader.Visible = true;
lblUser.Text = insUserPrincipal.GivenName + " " + insUserPrincipal.Surname;
lblEmail.Text = insUserPrincipal.EmailAddress;
}
}
}
You must add runat="server" to your table tblUsers
var row =new System.Web.UI.HtmlControls.HtmlTableRow();
var cell = new System.Web.UI.HtmlControls.HtmlTableCell();
cell.InnerText = "New Cell";
row.Cells.Add(cell);
tblUsers.Rows.Add(row);
It would be one of some possible solutions:
Store your data in a collection
In every button click, update the data and put it in session
Bind the session data to a Repeater in your page (the binding code MUST be in Page_Load)
The Repeater markup would be something like this
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<table id="tblUsers" class="table table-bordered table-striped">
<tbody id="tbodyUser">
</HeaderTemplate>
<ItemTemplate>
<tr>
<asp:Label ID="lblHeader" Font-Bold="true" runat="server" Visible="<% #lblHeaderVisibilty %>">User to Access</asp:Label>
<td>
<asp:Label ID="lblUser" runat="server" Visible="<% #lblUserVisibilty %>"></asp:Label>
</td>
<td>
<asp:Label ID="lblEmail" runat="server" Visible="<% #lblEmailVisibilty %>"></asp:Label>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</tbody>
</table>
</FooterTemplate>
</asp:Repeater>

Categories