Finding Div present inside the data list on runtime - c#

I need to find the div which belongs my current clicked Link button from the code behind file in c#. Then i need to apply the class for that div. So far i tried to access by html table cell. But i cant able to access my div. So please any valuable suggestion to find the div?
<asp:DataList ID="DataList1" runat="server" OnItemCommand="DataList1_ItemCommand" style="width:100%">
<ItemTemplate>
<div runat="server" id="DivContent" style="padding-top: 25px; height: 65px;" align="center"
onmouseover="this.className='MsgClick'" onmouseout="this.className=''" >
<asp:LinkButton ID="LinkButton2" runat="server" Text='<%# Eval("UserName") %>' CommandName="show"
class="InnerMenuFont"></asp:LinkButton>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("AdminId") %>' Visible="False"></asp:Label>
<br />
</div>
<hr style="width: 80%" />
</ItemTemplate>
</asp:DataList>
In the above code i need to access the current div in the id "DivContent"
.MsgClick
{
background-image: url('Images/AdminHighlight.png');
background-repeat: no-repeat;
vertical-align: top;
margin-right: -38px;
padding-right: 30px;
}
above code is my class file.

use below code
Control objDiv = e.Item.FindControl("DivContent");
hope it will help you

Might be wrong, but I don't believe it's possible to access a div from code behind if the div is part of a data bound control (DataList, GridView, etc), even if you have runat="server" set.
You can however swap the div for asp:Panel - which renders as a div when the page is served up to the browser. e.g.
<asp:Panel ID="DivContent" runat="server">
div content... LinkButton, Label etc...
</asp:Panel>
When the LinkButton is clicked, you can find the asp:Panel in your code behind using the item index of the DataList to which the LinkButton belongs:
LinkButton OnClick event:
protected void LinkButton2_Click(object sender, EventArgs e)
{
// Get the Link Button which has been clicked.
LinkButton btn = (LinkButton)sender;
// Get the DataListItem in the DataList which contains the LinkButton which was clicked.
DataListItem listItem = (DataListItem)btn.NamingContainer;
// Get the ItemIndex of the DataListItem.
int itemIndex = listItem.ItemIndex;
// Find the asp:Panel in the DataListItem of the DataList (e.g. DataList1).
Panel currentPanel = (Panel)DataList1.Items[itemIndex].FindControl("DivContent");
}
You should then hopefully be able to change style settings form code behind.
You could possibly use the CssClass property to change what you need:
...
Panel currentPanel = (Panel)DataList1.Items[itemIndex].FindControl("DivContent");
currentPanel.CssClass = "NewClassName";

Just did this myself good sir. There is a much simpler solution!
From your c# code behind, a div would be refereed to as type HtmlGenericControl.
You will need to add a onitemdatabound="DataList1_ItemDataBound" to your DataList control markup.
Inside your itemdatabound event you can modify the div.
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
// Find the div control as htmlgenericcontrol type, if found apply style
System.Web.UI.HtmlControls.HtmlGenericControl div = (System.Web.UI.HtmlControls.HtmlGenericControl)e.Item.FindControl("DivContent");
if(div != null)
div.Style.Add("border-color", "Red");
}

Related

How to find table cell in asp.net using c#

I want to hide an itemtemplate's data in listview using the td visibility property. Once I click a button it should show the data again that's within the itemtemplate. However, I cannot find the td control using c# in the code behind. Is there a way to find this control or another way to handle this?
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<asp:Button ID="Button1" runat="server" Text="Search" OnClick="ButtonClick" />
<asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0">
<asp:View ID="View1" runat="server">
<asp:ListView ID="SectionListView" runat="server" InsertItemPosition="FirstItem" OnPagePropertiesChanged="SectionListView_PagePropertiesChanged">
<ItemTemplate>
<tr style="">
<td></td>
<td id="row1" style="visibility:hidden;" runat="server">
<asp:Label ID="SectionItemLabel" runat="server" Text='<%# Eval("SectionItem") %>' />
</td>
</tr>
</ItemTemplate>
Here is part of the code for the button click:
protected void ButtonClick(object sender, EventArgs e)
{
var temp = (System.Web.UI.HtmlControls.HtmlTableCell)Page.Master.FindControl("MainContent").FindControl("row1");
}
You have a couple of issues. First, when you try to find "row1" within "MainContent", if won't find it because "row1" is actually a child of other children of "MainContent". It won't find them recursively unless you tell them to.
Second, since each ListViewItem within your ListView contains "row1", they are each given their own unique ID, such as SectionListView_ctrl0_row1, SectionListView_ctrl1_row1, etc. Because of this, you need to use FindControl() on each ListViewItem.
But, because you need to do it on each ListViewItem and because each ListViewItem contains "row1", each row will get the same property (i.e. all visible or all invisible). Here is how that could be done:
protected void ButtonClick(object sender, EventArgs e)
{
foreach (ListViewItem lvi in SectionListView.Items)
{
if (lvi.ItemType == ListViewItemType.DataItem)
{
HtmlTableCell row1 = (HtmlTableCell)lvi.FindControl("row1");
row1.Style.Add("visibility", "hidden");
}
}
}
If you need to style each cell individually, they would each need to be named differently. It is common to attach some sort of number or database ID to the end of the ID if that is the case.

Update TextBox after a button click

I have this TextBox:
<asp:TextBox id="locSelectedCameraGroupName" runat="server" ></asp:TextBox>
I have this back end code:
protected void btnCameraGroup_ServerClick(object sender, EventArgs e)
{
locSelectedCameraGroupName.Text = "test string!";
}
This method is called after clicking a button:
<asp:linkbutton id="btnCameraGroup" runat="server" onclick="btnCameraGroup_ServerClick" onclientclick="ShowCameraGroupPopup()"
style="font-size: 1.2em; text-decoration: none; cursor: pointer; background-color:grey; ">
<!-- TODO: Make button have round corners...css? -->
</asp:linkbutton>
However, the text does not update. This is a user control. The line is reached (according to my debugger). When I move the line to my page load, it works. Is there something wrong I am doing?
The following method ShowCameraGroupPopup just shows/hides some tags I don't think it has much to do with the issue, but here it is anyways:
function ShowCameraGroupPopup() {
$('#<%=waitIcon.ClientID%>').show();
$('#<%=divMainContent.ClientID%>').hide();
$("#divCameraGroupPopup").modal("show");
return true;
}
This is the flow after clicking the link button:
Page_Load hit (is post back)
btnCameraGroup_ServerClick hit
Tab name = Second tab (this is the info I want, but for some reason the
text isn't updated)
I needed an UpdatePanel (and ContentTemplate) around the TextBox with a Triggers (AsyncPostBackTrigger) as so:
<asp:UpdatePanel id="groupNamePanel" runat="server" updatemode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnCameraGroup" />
</Triggers>
<ContentTemplate>
<asp:TextBox id="locSelectedCameraGroupName" runat="server" ></asp:TextBox>
</ContentTemplate>
</asp:UpdatePanel>
If you have Page_Load() event in your codes, change Page_Load() content like below:
private void Page_Load()
{
if (!Page.IsPostBack)
{
//copy previous page load codes here
}
}

How to retrieve details from a repeater control to display in modal popup

I have a repeater control which displays an image and some basic information like DateTime and Prouct Id. On clicking an Image I need to run another query and show details in a seperate popup.I know how to do the popup.
I want to know how I can fetch the DateTime and ProductId from the repeater and use them in the button click event of the image?
I have my code for the repeater below :
<asp:Repeater ID="rptMonitorSummary" runat="server" OnItemDataBound="rptMonitorSummary_OnItemDataBound">
<ItemTemplate>
<asp:Panel ID="Pnl" runat="server">
<li class="ui-widget-content ui-corner-tr">
<h5 class="ui-widget-header">
<%# Eval("Name").ToString().Length > 9 ? (Eval("Name") as string).Substring(0, 9) : Eval("Name")%>
</h5>
<div id="divHover">
<asp:ImageButton Width="80px" ID="btnPerformanceImage" onclick="btnPerformanceImage_Click" runat="server" Height="45px">
</asp:ImageButton>
</div>
<div class="tooltip" style="display: none">
<div style="text-align: center; font-weight: bold;">
<%# Eval("DateTime") %><br />
</div>
<div style="text-align: center; font-weight: normal">
ErrorRatingCalls =
<%# Eval("ProductId")%><br />
</div>
<div style="text-align: center; font-weight: normal">
TotalRatingCalls =
<%# Eval("TotalCalls")%>
<br />
</div>
<div style="text-align: center; font-weight: normal">
SuccessRate =
<%# Eval("PassPercentage") + "%" %>
</div>
</div>
</li>
</asp:Panel>
</ItemTemplate>
</asp:Repeater>
I also have the button click event below :
protected void btnPerformanceImage_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript
(this, this.GetType(), "callScriptFunction", "ViewModelPopup1();", true);
}
All I want to know is how I can fetch the values that are already bound to the repeater control, When I click on an image which inside the repeater control
Instead of handling click on the button itself, you should rather make use of ItemCommand event of the Repeater control. As a CommandArgument you can pass ProductId, and then inside the handler use it to retrieve rest of the info from the DB. Or you can even include all needed values into CommandArgument as a single string and do some parsing afterwards:
<asp:Repeater ... OnItemCommand="rptMonitorSummary_ItemCommand" ... >
...
<asp:ImageButton ... CommandName="ShowPopup" CommandArgument='<%# Eval("ProductId") + "," + Eval("DateTime") %>'>
</asp:ImageButton>
...
</asp:Repeater>
The handler might look like this:
protected void rptMonitorSummary_ItemCommand(object sender, RepeaterCommandEventArgs e)
{
string[] tokens = e.CommandArgument.ToString().Split(',');
int productId = int.Parse(tokens[0]);
DateTime dateTime = Date.Time.Parse(tokens[1]);
// the rest of the handling here
}
Use the OnItemCommand event to fetch values out of the repeater control.
<asp:Repeater ID="rptMonitorSummary" runat="server" OnItemDataBound="rptMonitorSummary_OnItemDataBound" OnItemCommand="rptMonitorSummary_ItemCommand">
.
.
.
<asp:ImageButton Width="80px" ID="btnPerformanceImage" CommandName="Popup" runat="server" Height="45px"></asp:ImageButton>
.
.
.
protected void rptMonitorSummary_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "Popup")
{
DataRowView row = ((DataRowView)e.Item.DataItem).Row;
string data1 = Convert.ToString(row["Data1"]);
string data2 = Convert.ToString(row["Data2"]);
ScriptManager.RegisterStartupScript
(this, this.GetType(), string.Format("callScriptFunction", "ViewModelPopup1('{0}','{1}');", data1, data2), true);
}
}
Rather than the OnClick inside your Button, use the OnItemCommand="rptMonitorSummary_ItemCommand" in your Repeater
Then on the code behind
protected void rptMonitorSummary_ItemCommand(object sender, RepeaterCommandEventArgs e)
{
// e.CommandName and e.CommandArgument will let you know what was clicked
}
Your button can look something like this
<asp:Button runat="server" ID="btnPerformanceImage" Text="Whatever" CommandName="OpenImage" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "ProductId") %>' />
So then you know what the user clicked on and can change the popup to suit it
you can set a class attribute name for both div tags wich contains the date value and ProductId value and next get them with jquery .find('classname') to retreive their values.

ASP.NET Button OnClick within Repeater and LoginView

I'm developing a ASP.NET website with a C# backend. I'm having a problem with how to set an onclick event for buttons that are nested inside of both a loginview and a repeater. The code works fine for displaying all of the other data (anonymous view displays only an error message) but right now the buttons just redirect to the same page and remove the repeater and all contents, whereas they're supposed to run a specific delete function. The repeater, as it is right now, uses an alternatingitem template. If I remove the buttons from the nested controls, they work. I've tried this with buttons, linkbuttons, and imagebuttons. I'd rather use the latter, if possible. Is it possible to assign an Onclick to these buttons if they're nested like this? If not, what approach should I use?
<asp:LoginView ID="LoginLinksView" runat="server" EnableViewState="false">
<AnonymousTemplate>
<asp:Label ID="errorlabel" runat="server"></asp:Label>
</AnonymousTemplate>
<LoggedInTemplate>
<asp:Repeater id="Repeater" runat="server" >
<HeaderTemplate>
<table cellspacing="0" cellpadding="0">
<thead></thead>
</HeaderTemplate>
<ItemTemplate>
<tr class="Repeaterrow">
<!--Additional code here-->
<asp:ImageButton ID="delbutton" runat="server" ImageUrl=
"~/Images/delete.png" Onclick="DeleteOnClick"/>
</tr>
</ItemTemplate>
<AlternatingItemTemplate>
<tr class="Repeaterrow">
<!--Additional code here-->
<asp:ImageButton ID="delbutton" runat="server" ImageUrl=
"~/Images/delete.png" Onclick="DeleteOnClick"/>
</tr>
</AlternatingItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</LoggedInTemplate>
</asp:LoginView>
Here are the problems with your approach
1- The button issues postback as it should. But you need to put some CommandArgument with to identify "key" or which row you are processing it for.
2- Re Bind your Repeater with source. Below is the sample code for you.
protected void Page_Load(object sender, EventArgs e)
{
BindRepeater();
}
private void BindRepeater()
{
List<int> items = new List<int>();
for (int i = 0; i < 10; i++)
{
items.Add(i);
}
Repeater.DataSource = items;
Repeater.DataBind();
}
protected void DeleteOnClick(object sender, EventArgs e)
{
ImageButton delbutton = (sender as ImageButton);
//1- call your method with passing in delbutton.CommandArgument - it will give you key/ whatever you like
//2- Rebind the Repeater here and that will bind controls again...
BindRepeater();
}
protected void Repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
ImageButton delbutton = (sender as RepeaterItem).FindControl("delbutton") as ImageButton;
if (delbutton != null)
{
delbutton.CommandArgument = (sender as RepeaterItem).ItemIndex.ToString();
}
}
and ASPX Repeater definition would change to
Thanks,
Riz

Get data from modalpopupextender's panel

I have a GridView and a column in GridView which has a linkButton that opens a modalpopupextender on click. I am able to bind data in popextender panel but now i want to retrieve data from that panel.
I am getting data from each GridRow like:
foreach (GridViewRow row in MyGridView.Rows)
{
Label Date = (Label)row.Cells[0].FindControl("DateId");
string date = Date.Text;
//Code to get linkButton(asp:ModalpopUpextender) and data from
//asp:panel of ModalpopUpextender
}
I have searched around for answers but wasn't able to find a solution to my problem.
Thanks in advance.
Assuming you are having a setup like this
<ajaxToolKit:ModalPopupExtender
ID="mdlPopup" runat="server" TargetControlID="btnShowPopup" PopupControlID="pnlPopup"
CancelControlID="btnClose" BackgroundCssClass="modalBackground" />
<asp:Panel ID="pnlPopup" runat="server" Width="500px" style="display:none">
<asp:UpdatePanel ID="updPnlCustomerDetail" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblCustomerDetail" runat="server" Text="Customer Detail" Width="95%" />
</ContentTemplate>
</asp:UpdatePanel>
You might try finding your panel first and then drill down to the required control.I would suggest putting this code in the row editing event
gridViewTest_RowEditing(object sender, GridViewEditEventArgs e)
{
gridViewTest.EditIndex=e.NewEditIndex;
Panel myPanel = (Panel)gridViewTest.Rows(gridViewTest.EditIndex).FindControl("pnlPopup");
Label myLabel = (Label)myPanel.Findcontrol("lblCustomerDetail");
}
//then do stuff with the label.
Thanks Abide for the useful post...finally i found the solution...
Panel.FindControl("ControlId");
does not work fine because somtimes panel is not added to the page.
we can use this code.It works fine.
foreach( Control cntrl in Panel.Controls )
{
if(cntrl.ID == "RequiredConteolId")
{
//your application code goes here...
}
}

Categories