HIde a Column in Repeater Control - c#

How do I hide a particular column in Asp Repeater ? I want to hide POwner in this case !
<ItemTemplate>
<tr>
<td>
<%#Eval("Priority") %>
</td>
<td>
<%#Eval("ProjectName") %>
</td>
<td>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("POwner") %>'></asp:Label>
</tr>
</ItemTemplate>
Adding this in code behind gives an error :s
public void Repeater1_ItemDatabound(Object Sender, RepeaterItemEventArgs e)
{
Repeater a =(Repeater)e.Item.FindControl("Label1");
a.Visible = false;
}

Label1 is a Label control and not Repeater, that's why you're getting an error
You also need to add an if condition so you only get the Label1 for items and not for header or footer.
Try with this
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
Label label = (Label)e.Item.FindControl("Label1");
label.Visible = false;
}

You should cast Label1 to a Label not to a repeater try this :
Label a =(Label)e.Item.FindControl("Label1");
a.Visible = false;

i suppose it's impossible. but i can be mistaken
maybe you can try to use following inside your item template:
<tr>
<td runat="server" visible='<%# expression %'>
......
</td>
<td>
....
</tr>
or use ListView control instead Repeater

Related

Update SQL from Checkbox in ListView

Goal: Update row(s) in SQL table when Checkbox inside ListView is clicked.
I would like to update the following columns from sql:
IsApproved
ApprovalType
I am able to find the checkbox in the row that is clicked from the Listview on the page. However, that is as far as I got. Current code below, as well as what I've tried and the subsequent errors.
Code:
aspx:
<asp:ListView ID="lstUsers" runat="server" ItemType="Program.Data.Table" DataKeyNames="ID" SelectMethod="lstUsers_GetData"
OnItemCommand="lstUsers_ItemCommand" DeleteMethod="lstUsers_DeleteItem" OnSorting="lstUsers_Sorting"
OnItemDataBound="lstUsers_ItemDataBound"
ItemPlaceholderID="litPlaceHolder" >
<LayoutTemplate>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Last Name</th>
<th>First Name</th>
<th>UserName</th>
<th>Approve User</th>
<td><%# Item.LastName %></td>
<td><%# Item.FirstName %></td>
<td><%# Item.UserName %></td>
<td> <asp:CheckBox ID="cbApproved" runat="server" AutoPostBack="true" OnCheckedChanged="Approve_Click" /> </td>
c#:
protected void Approve_Click(object sender, EventArgs e)
{
foreach (ListViewItem item in lstUsers.Items)
{
if ((item.FindControl("cbApproved") as CheckBox).Checked == true)
{
System.Diagnostics.Debug.WriteLine("it was checked!");
I've tried:
item.ColumnName -- but get error ListView does not contain a
definition for ''
item.DataItem -- the output displays what looks
like an object as a whole
(System.Web.UI.WebControls.ListViewDataItem)
item.DataItem.ColumnName
-- but get error Object does not contain a definition for ''
Do the column values im looking to update in SQL have to be displayed on the ASPX page?
I looked through:
https://msdn.microsoft.com/en-us/library/bb398790.aspx#ModifyingDataUsingTheListViewControl
Asp.Net CheckBoxList to update a SqlDataSource
Why not simply cast the sender to a CheckBox?
protected void Approve_Click(object sender, EventArgs e)
{
if ((sender as CheckBox).Checked == true)
{
System.Diagnostics.Debug.WriteLine("it was checked!");
}
}
You must bind data to the ListView inside an IsPostBack check for it to work.
UPDATE
What you want can be done easily with DataKeyNames. Add it to the ListView as a property.
<asp:ListView ID="ListView1" runat="server" DataKeyNames="IDColumn">
Then when the checkbox is changed read the correct key
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
ListView1.DataSource = Common.fillBooks();
ListView1.DataBind();
}
}
protected void Approve_Click(object sender, EventArgs e)
{
//cast the sender back to the checkbox
CheckBox cb = sender as CheckBox;
if (cb.Checked)
{
//get the parent of the parent (itemtemplate > listiew)
ListView lv = cb.Parent.Parent as ListView;
//get the dataitem from the namingcontainer
ListViewDataItem item = cb.NamingContainer as ListViewDataItem;
//get the correct datakey with the index of the dataitem
int ID = Convert.ToInt32(lv.DataKeys[item.DataItemIndex].Values[0]);
//update database here with the ID
}
}
ListView
<asp:ListView ID="ListView1" runat="server" DataKeyNames="id" ItemType="Namespace.Class">
<ItemTemplate>
<div class="table-responsive">
<table class="table">
<tr>
<td>
<asp:CheckBox ID="cbApproved" runat="server" AutoPostBack="true" OnCheckedChanged="Approve_Click" />
</td>
</tr>
</table>
</div>
</ItemTemplate>
</asp:ListView>
This is what is currently working for me. Too long to add in comment or clutter original post:
ASPX:
<ItemTemplate>
<tr>
<td><asp:Label ID="UserNameLabel" runat="server" Text='<%#Eval("UserName") %>' /></td>
<td> <asp:CheckBox ID="Approved" runat="server" AutoPostBack="true" OnCheckedChanged="Approve_Click" /> </td>
</tr>
</ItemTemplate>
Changed the ItemTemplate to use asp Label controls so I could reference them in the code behind:
protected void Approve_Click(object sender, EventArgs e)
{
foreach (ListViewItem item in listUsers.Items)
{
if ((item.FindControl("Approved") as CheckBox).Checked == true)
{
Label myLabel = (Label)item.FindControl("UserNameLabel");
try
{
IQueryable<SUR> user = null;
user = db.SURs.Where(m => !m.IsApproved && m.UserName == myLabel.Text);
if(user != null)
{
db.sp_SUA(user.FirstOrDefault().ID, SessionMgr.CurrentUserID.ToString(), "Manual");
db.SaveChanges();
}
Response.Redirect(Request.RawUrl);
}
catch(Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
}
}
}
Once getting the control that had the username, I check if the DB has a row with the same value
If so, use a stored procedure to update the DB
EDIT:
After refactoring, I was wondering if it would be more efficient to get rid of the foreach loop, and instead use the OnItemCommand property of ListView and set the OnCheckedChanged for the Checkbox to point to the ItemCommand method? My thinking is since I am not looping through each item, would having the array index be better in terms of Big O?
Code would be:
protected void listSTUFF_ItemCommand(object sender, ListViewCommandEventArgs e)
if (int.TryParse(list.DataKeys[e.Item.DisplayIndex].Value.ToString(), out id)) {
var myQuery = db.Table.Where(a=>a.ID == id).FirstOrDefault();
db.StoredProcedure(myQuery.ID)
db.SaveChanges();

jQuery is not finding Asp.net repeater alternating item

I have a repeater on my webforms page, with a list bounded to it. while binding the list, I also attach a data-id attribute to the tr. The problem is I need to use that id in a web service call from jQuery, I am testing whether I can get the id by logging the data-id attribute value when I click on a button from the repeater item, but from the looks of things, it only logs the Item and not the Alternating item.
Button one, three and five gets log every time I click them but when I click on button two and button four, nothing gets logged in the console. See code below.
Repeater Template
<asp:Repeater runat="server" ID="rptList" OnItemDataBound="rptList_OnItemDataBound">
<HeaderTemplate>
<table>
</HeaderTemplate>
<ItemTemplate>
<tr runat="server" id="trList">
<td runat="server" id="tdList"></td>
<td runat="server" id="tdBtnRemove">
<asp:Button runat="server" ID="btnRemove" CssClass="btnRemove" Text="Remove" OnClientClick="return false;"/></td>
</tr>
</ItemTemplate>
<AlternatingItemTemplate>
<tr runat="server" id="trList">
<td runat="server" id="tdList"></td>
<td runat="server" id="tdBtnRemove">
<asp:Button runat="server" ID="btnRemove" Text="Remove" OnClientClick="return false;"/></td>
</tr>
</AlternatingItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
List item
List<string> listObj = new List<string>(){"one", "two", "three", "four", "five"};
protected void rptList_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
string listItem = (string) e.Item.DataItem;
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
HtmlTableRow trList = (HtmlTableRow)e.Item.FindControl("trList");
trList.Attributes.Add("data-id", listItem);
HtmlTableCell tdList = (HtmlTableCell)e.Item.FindControl("tdList");
tdList.InnerHtml = listItem;
}
}
jQuery button click method:
$(".btnRemove").click(function () {
var dataAttributVal = $(this).closest("tr");
var datA = dataAttributVal.data('id');
console.log(datA);
});
Console result:
As stated in the comments, your AlternatingItemTemplate misses the CssClass="btnRemove" attribute.
For this reason your $(".btnRemove").click(... binding does not target the buttons in your AlternatingItemTemplate

accessing objects in listview after buttonclick in listviewitem

I'm trying to setup a usercontrol.
I've setup a usercontrol with a table incl table header. For each row a second usercontrol is issued displaying 1 row of the table. The line-usercontrol is embedded in a listview.
One cell of the listview contains a textbox, another cell contains a Button. The buttons for each row are using the same buttonclick event using a commandargument for finding the pressed button.
Is there somekind of way to get the value entered in the textbox of that specific line?
code header control:
<asp:Panel runat="server" ID="pnlUcHeader">
<table>
<thead>
<tr>
<th>...</th>
...
<th>Textbox Column</th>
<th>Button Column</th>
</tr>
</thead>
<asp:ListView runat="server" ID="lvUcItemsItem" OnItemDataBound="lvUcItems_ItemDataBound">
<ItemTemplate>
<uc1:Items runat="server" ID="ucItems" CssClass="normal" />
</ItemTemplate>
</asp:ListView>
</table>
code Item User control
<tr runat="server" id="serverRow">
<td>
<asp:Literal runat="server" ID="..."></asp:Literal></td>
<td>
<asp:TextBox runat="server" ID="tbItem"></asp:TextBox>
</td>
<td>
<asp:Button runat="server" ID="btnItem" Text="..." OnCommand="btnItem_Click"/>
</td>
code behind Item User control
protected void btnItem_Click(object sender, CommandEventArgs e)
{
var lineID = e.CommandArgument;
//TextBox tb = FindControl("tbAfhaalDatum)
???????
}
Is this possible in code behind or is there an option to use Javascript/Jquery to postback the value?
Kind regards
You have to access your control's NamingContainer to search for your text box:
protected void btnItem_Click(object sender, CommandEventArgs e)
{
var control = (Control)sender;
var container = control.NamingContainer;
var textBox = container.FindControl("tbItem") as TextBox;
if (textBox != null)
{
var lineID = e.CommandArgument;
var text = textBox.Text;
}
}

How to access a legend tag from code

I have the following data-bound repeater code :
<%--categories--%>
<asp:Repeater ID="CategoryRepeater" runat="server" OnItemDataBound="ItemBound">
<ItemTemplate>
<div class="groupbox">
<fieldset>
<legend><%# Container.DataItem %></legend>
<table>
<asp:Repeater ID="ItemRepeater" runat="server">
<ItemTemplate>
<tr>
<td>
<asp:CheckBox id="chkItem" runat="server" Text='<%# Eval("Text")%>' />
<asp:HiddenField id="pgNos" runat="server" Value='<%# Eval("PGNos")%>' />
<asp:Button ID="btnXRefs" Text="x-refs" runat="server" CssClass="xRefButton" OnClick="btnSelectXRefs_Click" />
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
</fieldset>
</div>
</ItemTemplate>
</asp:Repeater>
There is a repeater inside a repeater. How do I access the text inside the legend (<legend><%# Container.DataItem %></legend>) from code?
I tried :
foreach (RepeaterItem cr in CategoryRepeater.Items)
{
string heading = (string) cr.DataItem; // returns null
}
Container.DataItem is a runtime alias for the DataItem for this specific item in the bound list. For a Repeater which displays 10 rows of data, this is one row from the datasource...Basically, it's a specific row and at runtime you can get the Property Values from this row
I saw your above Mark Up...Seems like you are missing to mention the property of Data-Bound type Class like below.
<%# ((Your Class Name)Container.DataItem).Class Property Name %>
There is a repeater inside a repeater. How do I access the text inside
the legend (<%# Container.DataItem %>) from code?
As told by phemt.latd, you can change the Legend tag into server side control like below.
<legend id="lg" runat="server">
<%# ((Your Class Name)Container.DataItem).Class Property Name %>
</legend>
Now, in the Item-Bound Data Event, Find the Legend Control.
protected void rpt_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
HtmlGenericControl ctl = (HtmlGenericControl)e.Item.FindControl("lg");
ctl.InnerText //This is what will give you the result.
}
}
The legend tag that you use is not visible on server side. Is a client control and not a server one.
Try with this:
<legend id="myLegend" runat="server"><%# Container.DataItem %></legend>
Then in codebehind:
protected void ItemBound(Object sender, RepeaterItemEventArgs e)
{
if (e.Item.DataItem == null) return;
HtmlGenerics body = (HtmlGenerics)e.Item.FindControl("myLegend");
body.InnerText = "Foo";
}

C# Checkbox.Checked Property Not Reflecting Check Changes

I have a form with containing a datalist which is bound to a datasource which contains a list of items and a true/false flag. If true, the myCheck checkbox is checked:
<form id="myForm" runat="server">
<asp:Button ID="save" runat="server" Text="Save" OnClick="save_Click" />
<br />
<asp:DataList runat="server" id="myList" onitemdatabound="myList_ItemDataBound">
<HeaderTemplate>
<th>Item Name</th>
<th id="thCheck" runat="server">Check?</th>
</HeaderTemplate>
<ItemTemplate>
<td id="tdName" runat="server"><%# Eval("Name") %></td>
<td runat="server"><asp:CheckBox id="myCheck" runat="server" Checked="false" /></td>
</ItemTemplate>
</asp:DataList>
On clicking save, I want to see which items have been checked. I am using the following to iterate through the items in the datalist:
protected void save_Click(Object sender, EventArgs e)
{
String Name;
Boolean omit;
foreach (DataListItem item in myList.Items)
{
CheckBox omitCheck = (CheckBox)item.FindControl("myCheck");
if (omitCheck != null)
{
if (omitCheck.Checked == true) // This line is my problem!!
{
// do stuff
}
break;
}
}
FindControl appears to work ok and returns a checkbox, however the value is always false, even if I have checked some of the boxes. If I set the value of the checkboxes to True in the aspx page, omitCheck.Checked is always true. ViewState is not disabled.
I'm new to this so sure there is an obvious answer.
what does the myList_ItemDataBound function look like? I suspect it needs a !IsPostback to not override entered values on the postback

Categories