Get TextBox Text value in a button - c#

I'm trying to get the value of txt_MRP in the codebehind but it keeps giving me
The name "txt_MRP" doesn't exist in this current context
Why is this reference not available? How can I get it?
(The button that I am pressing is btn_add_to_cart_Click)
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-4">
<asp:DataList ID="DataList3" runat="server" DataSourceID="SqlDataSource1">
<ItemTemplate>
<ul id="etalage">
<li>
<img id="Img1" class="etalage_thumb_image" runat="server" src='<%# Eval("Fotografia1") %>' />
<img id="Img2" class="etalage_source_image" runat="server" src='<%# Eval("Fotografia2") %>' />
</li>
</ul>
<br />
</ItemTemplate>
</asp:DataList>
</div>
<div class="col-lg-6">
<asp:DataList ID="DataList1" runat="server" DataKeyField="ID" DataSourceID="SqlDataSource1" >
<ItemTemplate>
<div id="product_name_width">
<asp:Label ID="Product_nameLabel" runat="server" CssClass="product_name" Text='<%# Eval("Nombre") %>' />
<br />
</div>
<span id="rs">₡</span><asp:Label ID="MRPLabel" CssClass="price" runat="server" Text='<%# Eval("Precio") %>' />
<br />
<br />
<span id="brand_name">Marca</span>
<asp:Label ID="BrandLabel" runat="server" CssClass="brand" Text='<%# Eval("Marca") %>' />
<br />
</div>
<div class="form-group">
<label> Cantidad </label>
<asp:TextBox CssClass="form-control" ID="txt_MRP" runat="server" ></asp:TextBox>
</div>
<div id="buy_now_css" runat="server">
<ul>
<li>
<asp:Button ID="btn_add_to_cart" CssClass="btn btn-primary" runat="server" Text="Añadir al Carrito" OnClick="btn_add_to_cart_Click" />
</li>
<li>
<asp:Button ID="btn_buy_now" CssClass="btn btn-success" runat="server" Text="Comprar" OnClick="btn_buy_now_Click" />
</li>
</ul>
</div>
</ItemTemplate>
</asp:DataList>
<asp:DataList ID="DataList2" runat="server" DataKeyField="ID" DataSourceID="SqlDataSource1">
<ItemTemplate>
<h2>Descripcion</h2>
<div id="Description_width">
<asp:Label ID="DetailLabel" CssClass="description" runat="server" Text='<%# Eval("Descripcion") %>' />
</div>
</ItemTemplate>
</asp:DataList>
</div>
</div>

txt_MRP does not exist because it is in a DataList Control. It is only available inside the scope of the Control.
If you want to get the value you have to use another method.
Change the button event from Onclick to OnCommand and add a CommandName and set the ItemIndex as CommandArgument.
<asp:Button ID="btn_add_to_cart" CommandName="addToCart" CommandArgument='<%# Container.ItemIndex %>' CssClass="btn btn-primary" runat="server" Text="Añadir al Carrito" OnCommand="btn_add_to_cart_Command" />
And in code behind
protected void btn_add_to_cart_Command(object sender, CommandEventArgs e)
{
//check the correct commandname
if (e.CommandName == "addToCart")
{
//get the row number from the commandargument
int itemIndex = Convert.ToInt32(e.CommandArgument);
//find the texbox in the correct row with findcontrol
TextBox textBox = DataList1.Items[itemIndex].FindControl("txt_MRP") as TextBox;
//do stuff with the value
Label1.Text = textBox.Text;
}
}

You have to assign the delegate or button. For instance:
var button = new Button();
button.Click += new EventHandler("btnAddToCart");
You also may need a CommandArgument, to be able to send a specific value back. But to actually register the click event would be like the above.

Related

asp.net imagebutton access in listview

How can i change imageUrl in listview function. I tried some codes but not worked.
my codes
protected void DoTheCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "Button")
{
ImageButton img = (ImageButton)e.Item.FindControl("Button1");
img.ImageUrl = "/img/heartcirc.png";
html code
<asp:ListView ID="listUrunler" OnItemCommand="DoTheCommand" runat="server">
<ItemTemplate>
<div class="col-lg-3 col-md-6 mb-4 mb-lg-0">
<div class=" card-img-top rounded shadow-sm border-0">
<asp:ImageButton ID="ImageButton1" class="card-img" runat="server" ImageUrl='<%# Eval("urunResim") %>' PostBackUrl='<%# String.Format("UrunDetay.aspx?Id={0}",Eval("Id")) %>' />
<div class="card-body p-4">
<h5 class="card-title" style="margin-top: -20px"><%# Eval("urunBaslik") %></h5>
<div class="price text-success" style="justify-content: center; float: left;"><%# Eval("urunFiyat") %>TL</div>
<asp:ImageButton ID="Button1" runat="server" Width="20px" Height="20px" ImageUrl="/img/heart.png" CommandName="Button" CommandArgument='<%# Eval("Id") %>' Text="Add to Cart" />
<div style="clear: both;"></div>
</div>
</div>
</div>
</ItemTemplate>
</asp:ListView>
Thanks for helps.

AsyncFileUpload in Repeater in UpdatePanel

The AsyncFileUpload works. Only issue is the file name disappears when the LinkButton to repeat the AsyncFileUpload control is pressed. Is there a way to get and store the file name? FileName does not work. Not really keen on sharing code-behind but may do so if it is necessary to solve this issue.
<asp:UpdatePanel ID="LibraryResourceUpdatePanel" runat="server">
<ContentTemplate>
<div class="field-group list-of-resource">
<asp:Repeater ID="RptRequest" runat="server" OnItemDataBound="RptRequest_ItemDataBound">
<ItemTemplate>
<div class="resource">
<div class="remove-input">
<asp:LinkButton ID="LbRemoveRequest" CssClass="ic fa fa-minus-circle" runat="server" OnClick="LbRemoveRequest_Click" CausesValidation="false"></asp:LinkButton>
<span>Remove</span>
</div>
<h2>Details of Resources
<span class="counter">
<asp:Literal ID="LitCount" runat="server"></asp:Literal>
</span>
</h2>
<ul>
<li>
<fieldset class="form-group">
<legend>Accession No.</legend>
<asp:TextBox ID="TxbAccessionNumber" CssClass="form-control" runat="server" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="TxbAccessionNumber" ErrorMessage="Email is required" ForeColor="Red" Display="Dynamic" />
</fieldset>
</li>
<li>
<fieldset class="form-group">
<legend>Details</legend>
<asp:TextBox ID="TxbDetails" runat="server" Rows="4" TextMode="MultiLine" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="TxbDetails" ErrorMessage="Details are required" ForeColor="Red" Display="Dynamic" />
</fieldset>
</li>
<li>
<fieldset class="form-group">
<legend>Image</legend>
<ajaxToolkit:AsyncFileUpload runat="server"
ID="FileUpload" OnUploadedComplete="FileUpload_UploadedComplete" ClientIDMode="AutoID" PersistFile="true"/>
<asp:RequiredFieldValidator runat="server" ControlToValidate="FileUpload" ErrorMessage="File Upload required" ForeColor="Red" Display="Dynamic" />
</fieldset>
</li>
</ul>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
<div class="add-input">
<asp:LinkButton ID="LbAddRequest" CssClass="ic fa fa-plus-circle" runat="server" OnClick="LbAddRequest_Click" CausesValidation="false" ></asp:LinkButton>
<span>Add another request</span>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="LbAddRequest" EventName="click" />
</Triggers>
</asp:UpdatePanel>
First add command name to linkbutton and remove click event:
<asp:LinkButton ID="LbAddRequest" runat="server"
CommandName="AddRequest"></asp:LinkButton>
<span>Add another request</span>
And try this ItemCommand event in code-behind to get in work:
protected void RptRequest_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "AddRequest")
{
FileUpload myFileUpload = (FileUpload)e.Item.FindControl("FileUpload");
if (myFileUpload.HasFile)
{
try
{
string filename = Path.GetFileName(myFileUpload.FileName);
myFileUpload.SaveAs(Server.MapPath("~/") + filename);
myStatusLabel.Text = "Upload Success";
}
catch (Exception ex)
{
myStatusLabel.Text = "Upload Fail" + ex.Message;
}
}
else
{
myStatusLabel.Text = "myFileUpload Has No File";
}
}
}
Read detail here : https://forums.asp.net/t/1904302.aspx?FileUpload+Inside+a+Repeater+Can+t+Find+File

Edit Image and Delete Row from GridView using c# ASP.NET

I need to Edit and Delete Row of GridView using C# ASP.NET.
I tried once and able to fill the data in TextBox after click on Edit Button,But I have also one Image to Edit and what I need is when user will click on Edit Image, The Image will also Display in proper place to Edit.In case of Delete part I have Image in Anchor Tag and I need which event I should pass from GridView and define in code behind page so that I can do the operation.
faq.aspx:
<div class="col-md-6">
<label for="question" accesskey="T"><span class="required">*</span> Question</label>
<asp:TextBox ID="TextBox1" runat="server" size="30" value="" name="question" ></asp:TextBox>
<div id="noty" style="display:none;" runat="server"></div>
<label for="answer" accesskey="A"><span class="required">*</span> Answer</label>
<asp:TextBox ID="TextBox2" runat="server" size="30" value="" name="answer" ></asp:TextBox>
<div id="Div1" style="display:none;" runat="server"></div>
</div>
<div class="col-md-6 bannerimagefile">
<label for="insertimage" accesskey="B"><span class="required">*</span> Insert Image</label>
<asp:FileUpload runat="server" class="filestyle" data-size="lg" name="insertimage" id="FileUpload1" onchange="previewFile()" />
<label for="bannerimage" accesskey="V"><span class="required">*</span> View Image</label>
<div style="padding-bottom:10px;">
<asp:Image ID="Image3" runat="server" border="0" name="bannerimage" style="width:70px; height:70px;" />
</div>
<div class="clear"></div>
<asp:Button ID="Button1" runat="server" Text="Submit" class="submit"
onclick="Button1_Click" />
</div>
</div>
</div>
</div>
<!--end_1st_faq_add_div-->
<!--2nd_list_banner_view_div-->
<div class="widget-area">
<h2 class="widget-title"><strong>FAQ List</strong></h2><asp:HiddenField ID="HiddenField1" runat="server" />
<div class="streaming-table margin-top-zero padding-top-zero">
<div class="table-responsive">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
Width="100%" CssClass="table table-striped table-bordered margin-top-zero"
onselectedindexchanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:TemplateField HeaderText="Sl No">
<ItemTemplate>
<asp:Label ID="faqid" runat="server" Text='<%#Eval("FAQ_ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Question" >
<ItemTemplate>
<asp:Label ID="question" runat="server" Text='<%#Eval("Question") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Answer" >
<ItemTemplate>
<asp:Label ID="answer" runat="server" Text='<%#Eval("Answer") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Image" >
<ItemTemplate>
<asp:Image ID="Image1" runat="server" border="0" name="bannerimage" style="width:70px; height:70px;" ImageUrl='<%# "/Upload/" + Convert.ToString(Eval("Image")) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action" >
<ItemTemplate>
</i>
<a href=" " data-toggle="tooltip" title="" class="btn btn-xs btn-danger" data-original-title="Delete"><i class="fa fa-times"></i>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
faq.aspx.cs:
protected void GridView1_SelectedIndexChanged(object sender, GridViewSelectEventArgs e)
{
int index = Convert.ToInt32(e.NewSelectedIndex);
TextBox1.Text = GridView1.Rows[index].Cells[1].Text;
TextBox2.Text = GridView1.Rows[index].Cells[2].Text;
HiddenField1.Value = GridView1.Rows[index].Cells[0].Text;
Button1.Text = "Update";
}
Please help me to resolve this issue.
I see that you have only item temples in grid view.
Hence I'm going to tell you two ways to do this:
1) Add edit template in grid view and handle the OnRowEditing event of grid view.
2) Add a hyperlink with key of row and link to another page where you can design the editor like you have done in this page by pre-populating the data using the key(primary key)
it is better that you use Modern data control like 'entitydataSource' or 'linqdateSource' or 'sqlDataSource' and bind your gridview by them .
using 'itemtemplate' for all rows is not a good way , instead fill you grid with 'dataSource' and use 'itemTemplate' for delete or Edit Button . send button name As commandName and rowID As commandArgument to gridViewItemCommand event in code behind.
in code behindin in GridviewItemcommand_Event with switch statement loop through itemCommands like this :
int itemID = int.parse(e.commandArgument)
switch(e.commandName)
{
case 'DoEdite' :{//some Code
Viewstate["ID"] = itemID;
break;}
case 'DoDelete' :{//some Code
break;}
}
you have the itemID(e.commandeArgument) and know which button clicked(e.commandName) .so you can do what you want.
In edit Mode when you send data to textBoxes use viewstate or other collection to hold your dataID because of after Edit, for Update edited date
you need it,

Response of link button inside update panel is too late in asp.net C#

When I click on Flag button all operation to be perform by button click are working very well but it take nearly 7 8 seconds to Show effects on screen..
My Asp.net code:
<asp:ScriptManager runat="server" EnablePartialRendering="true" ID="SC1"></asp:ScriptManager>
<!-- Get Mile-->
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-7">
<%-- <asp:UpdatePanel runat="server" ID="UpdatePanel1">
<ContentTemplate>--%>
<ul class="timeline-list">
<asp:Repeater runat="server" ID="repeater_post" OnItemDataBound="repeater_post_ItemDataBound" OnItemCreated="repeater_post_ItemCreated">
<ItemTemplate>
<li class="media media-clearfix-xs">
<div class="media-body">
<div class="media-body-wrapper">
<div class="panel panel-default ">
<asp:Image runat="server" ID="img_PostPic" ImageUrl='<%# GetImagePath(Eval("ImagePath").ToString()) %>' CssClass="img-responsive" Style="height: 200px !important; width: 526px !important" />
<%--<asp:Image runat="server" ID="Image1" ImageUrl='<%# GetMood(Eval("Mood").ToString()) %>' class="pull-right" />--%>
<div class="view-all-comments">
<asp:UpdatePanel runat="server" ID="upd5" UpdateMode="Always">
<ContentTemplate>
<asp:LinkButton runat="server" CommandArgument='<%# Eval("PostID").ToString() %>' ID="lbtn_Flag" CssClass="btn btn-white" ToolTip='<%# GetAllFlagMember(Convert.ToString(Eval("PostID"))) %>' OnClick="lbtn_Flag_Click" Visible='<%# CheckFlag(Eval("PostID"))%>'>
<i class="fa fa-flag"></i>
</asp:LinkButton>
<asp:LinkButton runat="server" CommandArgument='<%# Eval("PostID") %>' ID="lbtn_Unflag" CssClass="btn btn-white" ToolTip='<%# GetAllFlagMember(Convert.ToString(Eval("PostID"))) %>' OnClick="lbtn_Unflag_Click" Visible='<%# CheckUnFlag(Eval("PostID"))%>'>
<i class="fa fa-flag"></i> Unflag
</asp:LinkButton>
<strong> <%# GetFlagCount(Eval("PostID").ToString())%> Flag</strong>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="lbtn_Flag" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="lbtn_Unflag" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<%--<asp:LinkButton runat="server" ID="lbtnflagmember" CommandArgument='<%# Eval("PostID")%>' Text='<%# GetFlagCount(Eval("PostID").ToString())%>'></asp:LinkButton>--%>
<!-- Go to www.addthis.com/dashboard to customize your tools -->
<div class="addthis_sharing_toolbox" style="float: right"></div>
<asp:LinkButton runat="server" CommandArgument='<%# Eval("Lat")+"$"+Eval("Long")+"$"+Eval("PostAutorID")+"$"+Eval("Destination") %>' ID="lbtn_MapCanvas" ToolTip="Map" OnClick="lbtn_MapCanvas_Click" CssClass="pull-right" CausesValidation="false"> <i class="fa fa-map-marker"></i> Navigate
</asp:LinkButton>
<asp:LinkButton runat="server" CommandArgument='<%# Eval("PostID")+"$"+Eval("Destination") %>' ID="lbtn_ReportAbuse" ToolTip="Report Abuse" OnClick="lbtn_ReportAbuse_Click" CssClass="pull-right"> <i class="fa fa-share-square-o "></i> Report Abuse
</asp:LinkButton>
</div>
</div>
</div>
</div>
</li>
</ItemTemplate>
</asp:Repeater>
</ul>
My C# Back end Code on link buttons is :
protected void lbtn_Flag_Click(object sender, EventArgs e)
{
//lbtn_Flag.Enabled = false;
//lbtn_Unflag.Enabled = true;
LinkButton btn = (LinkButton)sender;
int _PostId = Convert.ToInt32(btn.CommandArgument);
WStblFlag wsFlag = new WStblFlag();
string res = wsFlag.AddFlag(_PostId, Functions.ParseInteger(Convert.ToString(Session["ProfileID"])));
GetPost();
//UpdatePanel up = repeater_post.FindControl("upd5") as UpdatePanel;
//up.Update();
//UpdatePanel inner_rpt = (UpdatePanel)repeater_post.Items.FindControl("repeater_Comment");
}
/// <summary>
/// UnFlag the post
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void lbtn_Unflag_Click(object sender, EventArgs e)
{
//lbtn_Flag.Enabled = true;
//lbtn_Unflag.Enabled = false;
LinkButton btn = (LinkButton)sender;
int _PostId = Convert.ToInt32(btn.CommandArgument);
WStblFlag wsFlag = new WStblFlag();
string res = wsFlag.UnFlagPost(_PostId, Functions.ParseInteger(Convert.ToString(Session["ProfileID"])));
GetPost();
}
I already try many things to reduce response time but it wont succeed...
Ty..

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