how to access controls in ListView EditItemTemplate - c#

I have a problem with EditItemTemplate.
I'm using Telerik RadUpload in asp listView.
In validating Event of radUpload, I want to check some Requirements so I need to findControl two control: radUpload and Label
For this I am using ItemDataBound Event of listView
but the problem is here, first ItemDataBound event execute and after that RadUpload Validating event will execute, therefor the radUpload Control and Label control remain empty
I handle this in a way by using static control, but i think that is not good idea.
Do you have a solution for that?
Another problem is with label. However I using static label and in trace shows the label have text but in output label not seen
<asp:ListView ID="LvAdminRing" runat="server" ItemPlaceholderID="ItemPlaceHolder" GroupPlaceholderID="GroupPlaceHolder"
OnItemEditing="LvAdminRing_ItemEditing" OnItemDataBound="onItemDataBound" OnItemUpdating="LvAdminRing_ItemUpdating">
<LayoutTemplate>
<div>
<asp:PlaceHolder runat="server" ID="GroupPlaceHolder"></asp:PlaceHolder>
</div>
</LayoutTemplate>
<GroupTemplate>
<div>
<asp:PlaceHolder runat="server" ID="ItemPlaceHolder"></asp:PlaceHolder>
</div>
</GroupTemplate>
<ItemTemplate>
<div class="RadRingTileDIV col-lg-12" runat="server">
<div class="row RadRingItemsDIV">
<asp:Label ID="lblPrice" CssClass="CustDispBlock CustItemFonts" runat="server" Text='<%# Eval("XPrice")%>'></asp:Label>
<asp:Label ID="lblCode" CssClass="CustDispBlock CustItemFonts" runat="server" Text='<%# Eval("XCode") %>'></asp:Label>
</div>
<div class="row RadRingItemsDIV ">
<asp:ImageButton ID="ImgRingEdit" runat="server" CommandName="Edit" ImageUrl="~/Image/Admin/CommandsPic/Edit.gif" />
<asp:ImageButton ID="ImgRingDel" runat="server" CommandName="Delete" ImageUrl="~/Image/Admin/CommandsPic/Delete.gif" />
</div>
</div>
</ItemTemplate>
<EditItemTemplate>
<div class="RadRingTileDIV col-lg-12" runat="server">
<div class="RadRingItemsDIV row">
<img src="ksdla" class="AdminImg CustDispBlock" />
<telerik:RadUpload ID="RupAdminRingPic" runat="server" AllowedFileExtensions=".png,.jpg,.jpeg,.jpe" AllowedMimeTypes="image/png,image/x-png,image/jpeg,image/pjpeg"
MaxFileInputsCount="1" MaxFileSize="52000" OverwriteExistingFiles="False" TargetFolder="~/Image/Products/Ring"
OnValidatingFile="RupAdminRingPic_ValidatingFile" ToolTip="انتخاب عکس جدید با پسوند های png،jpg،jpeg و jpe" ControlObjectsVisibility="CheckBoxes">
</telerik:RadUpload>
</div>
<div class="row RadRingItemsDIV">
<br />
<asp:Button ID="Button1" runat="server" Text="test" CommandName="Update" />
</div>
<div class="row RadRingItemsDIV">
<br />
<asp:Label ID="LblError" CssClass="CustDispBlock CustZ-Index" Visible="false" runat="server" Text=""></asp:Label>
</div>
</div>
</EditItemTemplate>
</asp:ListView>
public static Label lblError;
public static RadUpload RuEditPic;
public static Label lblError;
protected void RupAdminRingPic_ValidatingFile(object sender, Telerik.Web.UI.Upload.ValidateFileEventArgs e)
{
//Label test = (Label)LvItems.FindControl("LblError");
string[] AllowedFileExt = RuEditPic.AllowedFileExtensions;
foreach ( string AllowedExt in AllowedFileExt )
{
if (e.UploadedFile.ContentLength > RuEditPic.MaxFileSize)
{
lblError.Text = "some error";
lblError.Visible = true;
}
}
}
protected void onItemDataBound(object sender, ListViewItemEventArgs e)
{
int x = (e.Item as ListViewDataItem).DataItemIndex;
if (LvAdminRing.EditIndex == (e.Item as ListViewDataItem).DataItemIndex)
{
LvItems = LvAdminRing.Items as ListViewDataItem;
lblError = (e.Item.FindControl("LblError") as Label);
//errNoti = (e.Item.FindControl("LblError") as Label);
RuEditPic = (e.Item.FindControl("RupAdminRingPic") as RadUpload);
}
}

You should try this.
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
ListViewDataItem dataItem = (ListViewDataItem)e.Item;
if (dataItem.DisplayIndex == ListView1.EditIndex)
{
TextBox tb = e.Item.FindControl("tbFK_MenuID") as TextBox;
}
}
}

Related

Get LinkButton Embedded Label value

Get LinkButton Embedded Label value?
Also issue with LinkButton on postback comes back empty.
I basically need a clickable row to run a server side function is there a better way then a LinkButton?
I'm basically creating a search dropdown.
ASPX
<asp:ListView ID="listView" runat="server" ShowFooter="true" AutoGenerateColumns="false">
<ItemTemplate>
<asp:Repeater ID="SearchResults" OnItemCommand="SetValues_ItemCommand" runat="server">
<ItemTemplate>
<div class="form-row">
<asp:LinkButton ID="MemberInfo" runat="server" class="list-group-item list-group-item-action flex-column align-items-start mb-2" OnClick="MemberInfo_Click" CommandArgument='<%# Container.ItemIndex %>'>
<div class="col-lg-12 mb-2">
<h5 class="mb-1">
<asp:Label ID="PrimaryOrganization" runat="server" Text='<%# Eval("PrimaryOrganization") %>'></asp:Label>
</h5>
</div>
</asp:LinkButton>
</div>
</ItemTemplate>
</asp:Repeater>
CS
protected void MemberInfo_Click(object sender, EventArgs e)
{
LinkButton MemberInfoBNT = (LinkButton)sender;
bool bIsConverted = int.TryParse(MemberInfoBNT.CommandArgument.ToString(), out int index);
if (bIsConverted)
{
Repeater SearchResultsObject = MemberInfoBNT.Parent.Parent as Repeater;
ListViewDataItem listViewData = MemberInfoBNT.Parent.Parent.Parent as ListViewDataItem;
int Listviewindex = listViewData.DataItemIndex;
Label PrimaryOrganization = (Label)SearchResultsObject.Items[index].FindControl("PrimaryOrganization");
TextBox registrantEmailValue = (TextBox)listView.Items[Listviewindex].FindControl("registrantEmail");
registrantEmailValue.Text = PrimaryOrganization.Text;
}
}
Image of results
Select2 provides you a customizable dropdownlist with support for searching

Why doesn't my code access the control inside item template?

I have used panel inside template field and it disappears when I check a checkbox.
I tried fixing it but still disappears. The code works good while debugging but apparently not. Please help if you can. I have spent a lot of time on it already.
Code:
<asp:TemplateField HeaderText='Finalized ?'>
<ItemTemplate>
<asp:LinkButton ID="btnFinalizedRecord" OnClick="btnFinalizedRecord_Click" runat="server" Text='<%# Convert.ToBoolean(Eval("IsFinalized")) == true? "Already Finalized": "Finalize" %>'
CssClass="" ToolTip="Finalize" CommandName="Finalize"
CommandArgument='<%#Eval("IsFinalized")%>' Enabled='<%# Convert.ToBoolean(Eval("IsFinalized")) == true? false: true %>'></asp:LinkButton>
<ajax:ConfirmButtonExtender ID="ConfirmButtonExtender1" runat="server" DisplayModalPopupID="mpe2" TargetControlID="btnFinalizedRecord">
</ajax:ConfirmButtonExtender>
<ajax:ModalPopupExtender ID="mpe2" runat="server" PopupControlID="pnlPopup2" TargetControlID="btnFinalizedRecord" OkControlID="btnYes"
CancelControlID="btnNo" BackgroundCssClass="modalBackground">
</ajax:ModalPopupExtender>
<asp:Panel ID="pnlPopup2" runat="server" CssClass="modalPopup" Style="display: none">
<div class="header">
Confirmation
</div>
<div class="body">
Are you sure to <b>Finalize</b>?
<asp:CheckBox ID="chkConfirmFinalize" runat="server" AutoPostBack="true" OnCheckedChanged="chkConfirmFinalize_CheckedChanged" />
<br />
You will not be able to perform an edit after finalizing.
</div>
<div class="Popupfooter" align="right">
<asp:Button ID="btnYes" Enabled="false" CssClass="btn btn-sm btn-danger" runat="server" Text="Yes" />
<asp:Button ID="btnNo" CssClass="btn btn-sm btn-primary" runat="server" Text="No" />
</div>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
.cs code:
protected void chkConfirmFinalize_CheckedChanged(object sender, EventArgs e)
{
try
{
var chkConfirmFinalize = sender as CheckBox;
GridViewRow gr = (GridViewRow)chkConfirmFinalize.NamingContainer;
Panel pnlPopup2 = gr.FindControl("pnlPopup2") as Panel;
if (chkConfirmFinalize.Checked == true)
{
btnYes.Visible = true;
}
else
{
btnYes.Visible = false;
}
pnlPopup2.Visible = true;
}
catch (Exception ex)
{
Utility.Msg_Error(Master, ex.Message);
}
}

asp button doesn't invoke postback in usercontrol updatepanel

I have two asp buttons in my user control inside an update panel. But when I click them the postback is not completed (I have a java script alert set to page_load to tell me when a post back occurs, for example, it fires when the dropdownlist selection is changed). I can't figure out why the buttons are not posting back.
My usercontrol, the buttons in question are createBtn and signinBtn.
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Login.ascx.cs" Inherits="TestApp2.Views.Login" %>
<asp:UpdatePanel ID="LoginMainUpdatePanel" runat="server" UpdateMode="Conditional" OnUnload="UpdatePanel_Unload">
<ContentTemplate>
<asp:TextBox ID="infoTB" runat="server" TextMode="MultiLine" />
<div>
<div class="left-align" style="background-color:blue">
<asp:button runat="server" id="createBtn" CssClass="btn btn-default" OnClick="createBtn_Click" Text="Create" /><br/>
<asp:button runat="server" id="signinBtn" CssClass="btn btn-default" OnClick="signinBtn_Click" Text="Sign In" />
</div>
<!-- Login View -->
<div id="loginView" runat="server" class="centre-form centering text-center" style="background-color:green">
<h1>Login</h1>
<asp:Label ID="info" runat="server" Text="" />
<div class="form-group">
<label for="userIn">Username</label>
<asp:TextBox runat="server" id="userIn" CssClass="form-control" TextMode="SingleLine" />
<asp:RequiredFieldValidator runat="server" id="reqUser" controltovalidate="userIn" errormessage="Enter Username" />
</div>
<div class="form-group">
<label for="passwordIn">Password</label>
<asp:TextBox runat="server" id="passwordIn" CssClass="form-control" Text="Enter Password" TextMode="Password" />
<asp:RequiredFieldValidator runat="server" id="reqPass" controltovalidate="passwordIn" errormessage="Enter Password" />
</div>
<asp:Button runat="server" id="loginBtn" CssClass="btn btn-default" onclick="loginBtn_Click" text="Login" />
</div>
<!-- Create Account View -->
<div id="createView" runat="server" class="centre-form centering text-center" style="background-color:green">
<h1>Create</h1>
<div class="form-horizontal">
<div class="form-group" style="background-color:yellow;">
<asp:TextBox runat="server" id="personalFName" CssClass="form-control" TextMode="SingleLine" />
<label class="control-label" for="personalFName">First Name</label>
</div>
<div class="form-group">
<asp:TextBox runat="server" id="personalLName" CssClass="form-control" TextMode="SingleLine" />
<label class="control-label" for="personalLName" >Last Name</label>
</div>
<div class="form-group">
<asp:DropDownList runat="server" id="selGender" CssClass="form-control">
<asp:ListItem Value="Male" Text="Male" />
<asp:ListItem Value="Female" Text="Female" />
<asp:ListItem Value="Other" Text="Other" />
</asp:DropDownList>
<label class="control-label" for="selGender">Gender</label>
</div>
<asp:UpdatePanel ID="dobUpdatePanel" runat="server" UpdateMode="Conditional" OnUnload="UpdatePanel_Unload">
<ContentTemplate>
<div class="form-group">
<asp:DropDownList runat="server" id="selYear" CssClass="form-control" OnSelectedIndexChanged="selYear_SelectedIndexChanged" AutoPostBack="true" />
<asp:DropDownList runat="server" id="selMonth" CssClass="form-control" OnSelectedIndexChanged="selMonth_SelectedIndexChanged" AutoPostBack="true" />
<asp:DropDownList runat="server" id="selDay" CssClass="form-control"/>
<label class="control-label" for="selDay" >Date of Birth</label>
</div>
</COntentTemplate>
</asp:UpdatePanel>
</div>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
The code behind is as so
public partial class Login : System.Web.UI.UserControl
{
private DateMenu dobCtrl;
protected void Page_Load(object sender, EventArgs e)
{
if (Session[Paths.USERDETAILS] != null) Response.Redirect(Paths.USERCTRL_BASE + "Profile.ascx");
else setDetails();
}
protected void loginBtn_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
String SOAPbdy = "<Username>" + userIn.Text + "</Username><Password>" + passwordIn.Text + "</Password>";
HTTPRequest req = new HTTPRequest();
String response = req.HttpSOAPRequest(SOAPbdy, "GetUser");
infoTB.Text += response;
String uIDs = (new XMLParse(response)).getElementText("UserID");
int uID = 0;
Int32.TryParse(uIDs, out uID);
if (uID > 0)
{
Session["userDetails"] = response;
info.Text = "Success";
}
else info.Text = "Login failed";
}
}
private void setDetails()
{
if (dobCtrl == null) dobCtrl = new DateMenu(selYear, selMonth, selDay);
dobCtrl.setDateDropdown();
}
protected void UpdatePanel_Unload(object sender, EventArgs e)
{
MethodInfo methodInfo = typeof(ScriptManager).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
.Where(i => i.Name.Equals("System.Web.UI.IScriptManagerInternal.RegisterUpdatePanel")).First();
methodInfo.Invoke(ScriptManager.GetCurrent(Page),
new object[] { sender as UpdatePanel });
}
protected void selYear_SelectedIndexChanged(object sender, EventArgs e)
{
dobCtrl.fillDays();
}
protected void selMonth_SelectedIndexChanged(object sender, EventArgs e)
{
dobCtrl.fillDays();
}
protected void createBtn_Click(object sender, EventArgs e)
{
loginView.Visible = false;
}
protected void signinBtn_Click(object sender, EventArgs e)
{
}
}
I believe you have to register the controls for postback using
ScriptManager.RegisterPostbackControl()
https://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanager.registerpostbackcontrol%28v=vs.110%29.aspx
Try setting up the triggers for the UpdatePanel like so:
<asp:UpdatePanel ID="LoginMainUpdatePanel" runat="server" UpdateMode="Conditional" OnUnload="UpdatePanel_Unload">
<ContentTemplate>
<asp:TextBox ID="infoTB" runat="server" TextMode="MultiLine" />
<div>
<div class="left-align" style="background-color:blue">
<asp:button runat="server" id="createBtn" CssClass="btn btn-default" OnClick="createBtn_Click" Text="Create" /><br/>
<asp:button runat="server" id="signinBtn" CssClass="btn btn-default" OnClick="signinBtn_Click" Text="Sign In" />
</div>
[...]
</div>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="createBtn" />
<asp:PostBackTrigger ControlID="signinBtn" />
</Triggers>
</asp:UpdatePanel>
Try adding PostBackTriggers for the UpdatePanel.
Add 2 triggers one for each of the buttons.
<asp:UpdatePanel ID="myUpdatePanel" runat="server" UpdateMode="Conditional"ChildrenAsTriggers="false">
<ContentTemplate>
//Your Content
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="createBtn" />
<asp:PostBackTrigger ControlID="Signbtn" />
</Triggers>
</asp:UpdatePanel>
It was because of the asp form validation, no postback (async or not) was occurring because the form wasn't valid. Removing that made it all work.

"Add To Cart" Button in DataList ASP.NET

I Need to Add a button Add To Cart in Data-list.
The problem is, When i Click on btn ADD Button, Datalist1_ItemCommand() is never reached, but a Postback event occurs
I need to Add a Button that reads the current item values & performs some operations on it.
ASP Code
<asp:DataList ID="DL_Products" runat="server" RepeatColumns="3" OnItemCommand="Datalist1_ItemCommand">
<ItemTemplate>
<div class="Item">
<div class="title">
<asp:Label ID="lbl_Brand" runat="server" Text='<%# Eval("Brand") %>'></asp:Label>
</div>
<div class="Info">
Price/Piece :
<asp:Label ID="lbl_Price" runat="server" Text='<%# Eval("Price") %>'></asp:Label>
Rs
<br />
<asp:Button ID="btn" CommandName="AddtoCart" runat="server" Text="Add" />
</div>
</div>
</ItemTemplate>
</asp:DataList>
C#/ Code Behind :
protected void Datalist1_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "AddtoCart")
{
Label l1 = (Label)e.Item.FindControl("lbl_Price");
string a = l1.Text;
Response.Write(l1.Text);
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
load_User_data();
Brand_SelectedIndexChanged(null, null);
load_data();
}
}
add if(!ispostback){ bind datalist} on page load

Access TextBox in DataList by ID from Button-Click handler in codebehind

I have a textbox which is kept inside Datalist. I need to find it via ID, so that i can insert text written to that textbox to the database.Here is my aspx page containing textbox.
<asp:Content ID="Content1" ContentPlaceHolderID="ccont" Runat="Server">
<div id="ccont">
<asp:DataList ID="mydatalist" ItemStyle-CssClass="lft_c_down" runat="server">
<ItemTemplate>
<div id="wholeC">
<div id="ctop">
<div id="lft_l">
<div id="lft_c_top">
<asp:Image runat="server" ImageUrl='<%#DataBinder.Eval(Container.DataItem,"ipath")%>' Height="250px" Width="300px" />
<br/>
</div>
<div id="lft_c_down">
<b>Product Name:</b>
<asp:Label ID="lbl2" Text='<%#DataBinder.Eval(Container.DataItem,"products") %>' runat="server" />
<br/>
<b>brand:</b>
<asp:Label ID="lbl1" Text='<%#DataBinder.Eval(Container.DataItem,"brand") %>' runat="server" />
<br/>
<b>Price:</b>
<asp:Label ID="Label1" Text='<%#DataBinder.Eval(Container.DataItem,"price") %>' runat="server" />
</div>
</div>
<div id="lft_r">
<b>Details:</b>
<asp:Label ID="Label2" Text='<%#DataBinder.Eval(Container.DataItem,"description") %>' runat="server" />
</div>
</div>
<div id="cmt">
<asp:TextBox ID="tb_cmt" runat="server" Height="35px" Width="620" placeholder="comment.." />
<asp:Button ID="Button1" runat="server" Text="Comment" backcolor="black" BorderStyle="None" Font-Names="Consolas" Font-Overline="False"
ForeColor="White" Height="34px" Width="108px" OnClick="cmt_Click" />
</div>
</div>
</ItemTemplate>
</asp:DataList>
</div>
The Textbox with ID="tb_cmt" is the text box i want to access in my code behind as:
protected void cmt_Click(object sender, EventArgs e)
{
// how to get the TextBox?
sq.connection();
SqlCommand cmd = new SqlCommand("insert into comment(ecomment,sid) values(#myecomment,#mysid)", sq.con);
cmd.Parameters.AddWithValue("#myecomment",tb_cmt.text)//but here tb_cmt is not recognized.
}
You can use the NamingContainer property of the button that was clicked to get the DataListItem. Then you just have to use FindControl to get the reference to your TextBox:
protected void cmt_Click(object sender, EventArgs e)
{
Button btn = (Button) sender;
DataListItem item = (DataListItem) btn.NamingContainer;
TextBox txt = (TextBox) item.FindControl("tb_cmt");
//... save
}

Categories

Resources