How To Get Value From ListView - c#

I have Code
<head>
<title><%=txtTitle.Text</title>
</head>
<asp:HiddenField ID="txtTitle" runat="server" />
<asp:ListView ID="lvDetNews" runat="server" DataSourceID="sdsBerita">
<ItemTemplate>
<asp:HiddenField ID="HFcari" runat="server" Value='<%# Eval("judul_berita") %>' />
<h2><%# Eval("judul_berita") %></a></h2>
</ItemTemplate>
</asp:ListView>
How to get Value HiddenField from Listview?
I'm tring this. But can't display
protected void Page_Load(object sender, EventArgs e)
{
HiddenField tt = (HiddenField)lvDetNews.FindControl("HFcari");
txtTitle.Value = "tess" + tt;
}

protected void Page_Load(object sender, EventArgs e)
{
HiddenField tt = (HiddenField)lvDetNews.FindControl("HFcari");
txtTitle.Value = "tess" + tt.Value;
}
Update:
You got that error because the listview was not binded yet, so i think the best way would be to do all this on the ItemDataBound event. You would find the hidden field like below:
<asp:ListView ID="lvDetNews" runat="server" DataSourceID="sdsBerita" OnItemDataBound="lvDetNews_ItemDataBound">
<ItemTemplate>
<asp:HiddenField ID="HFcari" runat="server" Value='<%# Eval("judul_berita") %>' />
<h2><%# Eval("judul_berita") %></a></h2>
</ItemTemplate>
</asp:ListView>
protected void lvDetNews_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
HiddenField tt = (HiddenField)e.Item.FindControl("HFcari");
txtTitle.Value = "tess" + tt.Value;
}
}

You need to change your code as below
protected void Page_Load(object sender, EventArgs e)
{
HiddenField tt = (HiddenField)lvDetNews.FindControl("HFcari");
txtTitle.Value = "tess" + tt.Value;
}

If you want to get value in page load , you should know the row number
var hiddenFld = this.lvDetNews.Items[<row_index>].FindControl("HFcari") as HiddenField;
string value = hiddenFld.Value();
Otherwise you have to done this in ItemDataBound event
<head>
<title><%=txtTitle.Text</title>
</head>
<asp:HiddenField ID="txtTitle" runat="server" />
<asp:ListView ID="lvDetNews" runat="server" DataSourceID="sdsBerita" OnItemDataBound="lvDetNews_ItemDataBound">
<ItemTemplate>
<asp:HiddenField ID="HFcari" runat="server" Value='<%# Eval("judul_berita") %>' />
<h2><%# Eval("judul_berita") %></a></h2>
</ItemTemplate>
</asp:ListView>
Code:
protected void lvDetNews_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
var hiddenFld = e.Item.FindControl("HFcari") as HiddenFiled;
string value = hiddenFld.Value();
// ...
}
}

Related

How to pass value to Click event using command argument Asp.Net WebForms C#

I have minimal knowledge of ASP.Net WebForms. Now I am facing a small issue. Here I am iterating list using foreach, while iterating I want to bind value linkbutton command argument. But OnCommand event I am not getting value.
MyCode:
.aspx
<%foreach (var item in model.ItemsWithoutDiscount) {%>
<asp:Button ID="Button1" runat="server" Text="Delete" CommandArgument='<%= item.ID %>' OnCommand="Button1_Click" />
<%}%>
This is my event on .aspx.cs
protected void Button1_Click(Object sender, CommandEventArgs e)
{
string ID = e.CommandArgument.ToString();
}
I want pass value in command argument to my event. Please help
**ASPX**
<asp:Repeater ID="Repeater1" runat="server" OnItemCommand="Repeater1_ItemCommand">
<ItemTemplate>
<asp:Button runat="server" CommandArgument='<%# Eval("ID") %>' Text="Delete" />
</ItemTemplate>
</asp:Repeater>
**C#**
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Repeater1.DataSource=YOUR_DATA_SOURCE;//ItemsWithoutDiscount
Repeater1.DataBind();
// ...
}
}
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandArgument == null)
return;
var id = int.Parse(e.CommandArgument.ToString());
// your logic here ...
}

How to access a child control of parent control from another child control?

I have a repeater control to show some pictures from a specified folder. Repeater has and image and a button inside to remove that image. But the problem how to reach that image name in button click event? This is my code below:
Aspx file:
<asp:Repeater ID="rptImage" runat="server">
<ItemTemplate>
<asp:Button id="btnDelete" runat="server" Text="DELETE" OnClick="btnDelete_Click" />
<asp:Image ID="image" runat="server" ImageUrl='<%# Container.DataItem %>' />
</ItemTemplate>
</asp:Repeater>
CS file:
private void getImages(string serialNo)
{
try
{
string[] filesindirectory = Directory.GetFiles(Server.MapPath("~/Images/" + serialNo + "/"));
List<String> images = new List<string>(filesindirectory.Count());
foreach (string item in filesindirectory)
{
images.Add(String.Format("~/Images/" + serialNo + "/{0}", System.IO.Path.GetFileName(item)));
}
rptImage.DataSource = images;
rptImage.DataBind();
}
catch (Exception)
{
header.Visible = true;
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
//string imgUrl;
//The url of image is all i need to delete it
}
Use CommandName, CommandArgument and OnCommand properties of Button.
protected void Btn_Click(object sender, CommandEventArgs e)
{
if (e.CommandName == "BtnClick"){
e.CommandArgument.ToString();
}
}
<asp:Repeater ID="rptImage" runat="server">
<ItemTemplate>
<asp:Button id="btnDelete" runat="server" Text="DELETE" OnCommand="Btn_Click" CommandName="Btn_Click" CommandArgument="<%# Container.DataItem %>" />
<asp:Image ID="image" runat="server" ImageUrl="<%# Container.DataItem %>" />
</ItemTemplate>
</asp:Repeater>

How to persist data in asp repeater on postback

Below is the markup page:
<%# Page Title="" Language="C#" MasterPageFile="~/Master/MainPage.master" EnableViewState="true" AutoEventWireup="true" CodeBehind="edit.aspx.cs" Inherits="Website.View.edit" %>
...
<asp:Repeater runat="server" ID="rptSample">
<ItemTemplate>
<asp:HyperLink runat="server" ID="refLink" href='http://www.sample.com' Text='Test data' />
<asp:CheckBox runat="server" ID="chkbxDelete" Text="Delete" />
</ItemTemplate>
<SeparatorTemplate>
<br />
</SeparatorTemplate>
</asp:Repeater>
Here's how I bind data on code behind:
protected void Page_Load(object sender, EventArgs e)
{
rptSample.DataSource = getData();
rptSample.DataBind();
}
I've also tried this one:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
rptSample.DataSource = getData();
rptSample.DataBind();
}
}
And tried to get the data on btnSave_Click function
protected void btn_save_Click(object sender, EventArgs e)
{
foreach(RepeaterItem item in rptSample.Items)
{
CheckBox chkbx = (CheckBox) item.FindControl("chkbxDelete");
if (chkbx.Checked)
{
//Do something
}
}
}
If I didn't add the !IsPostBack, the rptSample.Items will be empty but if I remove it, the checkbox will always be false.
What's the problem??
Edit:
As per a user requested, here's the full page load function:
protected void Page_Load(object sender, EventArgs e)
{
bindData();
}
protected void bindData()
{
List<sp_SelectAttachments_Result> attachments = DAL.SelectAttachmentsByID(Request["ID"]);
if (attachments.Count == 0)
divAttachments.Visible = false;
else
{
divAttachments.Visible = true;
rptAttachments.DataSource = attachments;
rptAttachments.DataBind();
}
}
Here's the markup page for divAttachments and rptAttachments
<div runat="server" id="divAttachments" visible="false">
<asp:Repeater runat="server" ID="rptAttachments">
<ItemTemplate>
<asp:HiddenField Value='<%# Eval("ID") %>' runat="server" ID="hidID" />
<asp:HyperLink runat="server" ID="refLink" href='<%# $"/Utils/getFile.ashx?ID={ID}" %>' Text='<%# ((sp_SelectAttachments_Result)Container.DataItem).FileName %>' />
<asp:CheckBox runat="server" ID="chkbxDeleteAttachment" Text="Delete" />
</ItemTemplate>
<SeparatorTemplate>
<br />
</SeparatorTemplate>
</asp:Repeater>
</div>
I suspect that there is something in your code which clears the check boxes or resets the data source of the repeater control.
I suggest creating a clean page and using the code below(which I've tested and it works).Once you have it working slowly start adding any additional logic to the page until you figure out what's causing the problem:
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
rptSample.DataSource = getData();
rptSample.DataBind();
}
}
private List<string> getData()
{
return new List<string> { "1", "2", "3" };
}
protected void btn_save_Click(object sender, EventArgs e)
{
foreach (RepeaterItem item in rptSample.Items)
{
CheckBox chkbx = (CheckBox)item.FindControl("chkbxDelete");
if (chkbx.Checked)
{
System.Diagnostics.Debugger.Break();
}
}
}
.ASPX:
<form id="form1" runat="server">
<asp:Repeater runat="server" ID="rptSample">
<ItemTemplate>
<asp:HyperLink runat="server" ID="refLink" href='http://www.sample.com' Text='Test data' />
<asp:CheckBox runat="server" ID="chkbxDelete" Text="Delete" />
</ItemTemplate>
<SeparatorTemplate>
<br />
</SeparatorTemplate>
</asp:Repeater>
<asp:Button ID="btn_save" runat="server" Text="Save" OnClick="btn_save_Click" />
</form>
Use Viewstate to hold data. bind viewstate to repeater on load and also use the !IsPostBack for rptSample.DataBind();

how to grab the Ctl from a linkbutton

I have a gridview which is pulling it data from a stored procedure. In the column title, I have used a Linkbutton. I would like to grab the Ctl ID and store it in a variable when it is clicked. I am not sure what is happening, but I get a few strings going through. Below is my code and this is similar to my previous post.
ASP.NET
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:LinkButton ID="lnkID" runat="server" OnClick="lblClick1"
Text='<%#Eval("ID") %>'>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
C#:
GridViewRow row = gv2.SelectedRow;
string controlId = ((LinkButton)row.FindControl("lnkID")).ID;
lblshow.Text = controlId;
Can someone help me get up and running. Thanks.
You could use a hidden field to store the id:
<ItemTemplate>
<asp:HiddenField
runat="server"
ID="ID"
Value='<%# Eval("ID") %>'
/>
<asp:LinkButton
runat="server"
OnClick="LabelClick"
Text="click me"
/>
</ItemTemplate>
and then:
protected void LabelClick(object sender, EventArgs e)
{
var hiddenField = (HiddenField)((Control)sender).FindControl("ID");
var id = hiddenField.Value;
// Do something with the id
}
UPDATE:
Full working example:
<%# Page Language="C#" %>
<script type="text/c#" runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
grid.DataSource = Enumerable.Range(1, 10).Select(x => new
{
ID = x
});
grid.DataBind();
}
}
protected void LabelClick(object sender, EventArgs e)
{
var hiddenField = (HiddenField)((Control)sender).FindControl("ID");
result.Text = string.Format("selected id: {0}", hiddenField.Value);
}
</script>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form id="Form1" runat="server">
<asp:GridView ID="grid" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:HiddenField
runat="server"
ID="ID"
Value='<%#Eval("ID") %>'
/>
<asp:LinkButton
runat="server"
OnClick="LabelClick"
Text="click me"
/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="result" runat="server" />
</form>
</body>
</html>
In the OnClick method lblClick1 you can use:
public void lblClick1(object sender, CommandEventArgs e)
{
int controlId = Convert.ToInt32(e.CommandArgument); //get ID and store it in controlId
lblshow.Text = controlId;
}

TextBox TextChanged Events not firing within a gridview

I've got a databound grid view within a UpdatePanel.
There are textboxes in the template fields which are dynamically created with a for loop.
I have a textChange event associated with each textbox, but the event isn't being fired.
Please help me with it.
Here's the ASP code:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<table width="100%">
<%--table for the grid view of buttons--%>
<tr>
<td align="center">
<asp:GridView ID="gvJV" runat="server" AutoGenerateColumns="False"
Height="100%" Width="749px" >
<Columns>
<asp:TemplateField HeaderText="Account">
<ItemTemplate>
<ajaxToolkit:ComboBox ID="AccountId" runat="server" AutoPostBack="false">
</ajaxToolkit:ComboBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="AccountId"
Display="Dynamic" ErrorMessage="Select Account" ForeColor="Red" InitialValue="-1">*</asp:RequiredFieldValidator>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="btnSelect" runat="server" ImageUrl="~/images/icons/edit.png" AutoPostBack="false"
ImageAlign="AbsMiddle" OnClientClick='hdCallerRowID.value = this.parentElement.parentElement.rowIndex-1;' />
<ajaxToolkit:ModalPopupExtender ID="gv_ModalPopupExtender" runat="server" TargetControlID="btnSelect"
PopupControlID="pnlSelectCOA" CancelControlID="btnCancel" BackgroundCssClass="modalBackground">
</ajaxToolkit:ModalPopupExtender>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Memo">
<ItemTemplate>
<asp:TextBox ID="txtMemo" runat="server" BorderStyle="None" AutoPostBack="false"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Debit">
<ItemTemplate>
<asp:TextBox ID="txtDebit" runat="server" AutoPostBack="false" OnTextChanged="txtDebit_textChanged" comm></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Credit">
<ItemTemplate>
<asp:TextBox ID="txtCredit" AutoPostBack="false" EnableViewState="true" runat="server" OnTextChanged="txtDebit_textChanged"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</asp:UpdatePanel>
and here's the code at back end
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ERP.Controller;
using System.Data;
using AjaxControlToolkit;
using MERP.WebUI.Code;
using ERP.Properties;
namespace MERP.WebUI.Account.GL
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txtCalendar_CalendarExtender.SelectedDate = DateTime.Now.Date;
BindGrid();
}
}
private void BindGrid()
{
DataTable dt = new DataTable();
dt.Columns.Add("Dummy");
for (int i = 0; i < 10; i++)
dt.Rows.Add("");
dt.AcceptChanges();
gvJV.DataSource = dt;
gvJV.DataBind();
}
private void SaveForm()
{
int debitTotal = 0;
int creditTotal = 0;
foreach (GridViewRow gvRow in gvJV.Rows)
{
TextBox txtDebit = (TextBox)gvRow.FindControl("txtDebit");
if (txtDebit.Text != string.Empty)
debitTotal += Convert.ToInt32(txtDebit.Text.Trim());
TextBox txtCredit = (TextBox)gvRow.FindControl("txtCredit");
if (txtCredit.Text != string.Empty)
creditTotal += Convert.ToInt32(txtCredit.Text.Trim());
}
if (debitTotal != creditTotal)
((Authenticated)Master).SetMessage("NOT EQUAL");
else
((Authenticated)Master).SetMessage("done successfully");
}
protected void gvJV_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ComboBox AccountId = (ComboBox)e.Row.FindControl("AccountId");
Common.BindAccounts(AccountId);
TextBox txtMemo = (TextBox)e.Row.FindControl("txtMemo");
}
}
protected void txtDebit_textChanged(object sender, EventArgs e)
{
GridViewRow row = ((GridViewRow)((TextBox)sender).NamingContainer);
//NamingContainer return the container that the control sits in
TextBox other = (TextBox)row.FindControl("txtCredit");
other.Text = "";
}
protected void btnCancel_Click(object sender, EventArgs e)
{
}
protected void btnSave_Click(object sender, EventArgs e)
{
SaveForm();
}
}
}
I had the same problem. I resolved it by setting the AutoPostBack of the TextBox to true. Therefore the code should be:
<ItemTemplate>
<asp:TextBox ID="txtMemo" runat="server" AutoPostBack="true"></asp:TextBox>
</ItemTemplate>

Categories