Change Label text in gridview on checking checkbox - asp.net

I am using this Gridview which have checkboxes and labels in it.Now I want when i click the checkbox the text of label must change.
<asp:GridView ID="grdData" runat="server" style="Text-align:center;">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" onclick="changeTextValue(this)"/>
</ItemTemplate>
<HeaderTemplate>
<%--<asp:CheckBox ID="CheckBox2" runat="server" OnClick="CheckAllEmp(this)"/>--%>
</HeaderTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="Status_Header" runat="server" Text="Status" />
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text=0 ClientIDMode="Static"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

First Question
Because the label rendered on html will be:
<span id="grdData_ctl02_Label1" ClientIDMode="Static">1</span>
So,you should use "span[id*='Label1']" to find it out:
function changeTextValue(chk) {
var currentTextID = $(chk).parents("tr").find("span[id*='Label1']");
if (chk.checked == true) {
currentTextID.html(1);
}
else {
currentTextID.html(0);
}
}
Second Question
Gridview
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" onclick="changeTextValue(this)" />
</ItemTemplate>
<HeaderTemplate>
<asp:CheckBox ID="CheckBox2" runat="server" OnClick="CheckAllEmp(this)" />
</HeaderTemplate>
</asp:TemplateField>
Javascript
function CheckAllEmp(chk) {
var currentTextID = $(chk).parents("table").find("span[id*='Label1']");
var childCheckBoxID = $(chk).parents("table").find("input[id*='CheckBox1']");
if (chk.checked == true) {
currentTextID.html(1);
childCheckBoxID.prop("checked", true);
}
else {
currentTextID.html(0);
childCheckBoxID.prop("checked", false);
}
}

For what reason do you use ClientIDMode="Static"?
You have to create function CheckAllEmp(this) event in your_program_file.cs.
Code in that function would be smth like that:
CheckAllEmp(...){
Label1.Text="Something new";
}

When you want this kind of operations on GridView, it is always good to check the html source of your page. In this scenario, for example, you will have the following html code for your gridview:
<table cellspacing="0" rules="all" border="1" id="grdData" style="border-collapse:collapse;text-align: center;">
<tr>
<th scope="col"></th>
<th scope="col">
<span id="grdData_Status_Header">Status</span>
</th>
</tr>
<tr>
<td>
<input id="grdData_CheckBox1_0" type="checkbox" name="grdData$ctl02$CheckBox1" onclick="changeTextValue(this);" />
</td>
<td>
<span id="Label1">Unique Perspective</span>
</td>
</tr>
<tr>
<td>
<input id="grdData_CheckBox1_1" type="checkbox" name="grdData$ctl03$CheckBox1" onclick="changeTextValue(this);" />
</td>
<td>
<span id="Label1">Challenging</span>
</td>
</tr>
</table>
As you may see, checkbox and label controls are in adjacent table cells. You can use .parent().next() to access the cell containing the label control. Also, you may see that label was rendered as span. To get the label control, therefore, you can use: .parent().next().find('span'). One final note is that you can use .text property of a span to change its contents. See the whole script below:
function changeTextValue(chk) {
var currentTextID = $(chk).parent().next().find('span');
if (chk.checked == true)
currentTextID.text('1');
else currentTextID.text('0');
}

Related

get the value of all the checked checkboxes on button click

I have created a table in my .aspx file that looks like this:
Here is the code that does this:
<!-- code for generating the "add selected sessions" button -->
<table>
<tr>
<td><strong>Individual Sessions</strong></td>
<td >
<div class="addButton" style="text-align: center;">
<asp:LinkButton ID="LinkButton2" runat="server" Text="Add Selected Sessions" OnClick="btnAddToCart_Click" />
</div>
</td>
</tr>
</table>
<!-- add all the sessions for the user to select -->
<asp:Repeater ID="rptFeesSession" runat="server">
<HeaderTemplate>
<table >
</HeaderTemplate>
<ItemTemplate>
<asp:HiddenField ID="hdnIsSession" runat="server" Value='<%#Eval("isSession")%>' />
<tr runat="server" visible='<%# Eval("isSession")%>'>
<td valign="top" colspan="2" style="position: relative;">
<asp:HyperLink CssClass="siteColorFG popBtn" ID="hlFeeType" runat="server" Text='<%#Eval("title")%>' NavigateUrl="javascript:;"/>
</td>
<td valign="top">
<div class="">
<asp:CheckBox ID="LinkButton3" CommandArgument='<%#Eval("id")%>'CssClass="checkB" OnClick="btnAddToCart_Click" runat="server" Text='<%#Eval("amount", "{0:C}")%>' />
</div>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
In my code behind file i want to capture all the checkboxes that have been checked and their respective CommandArgument values.
protected void btnAddToCart_Click(object sender, EventArgs e)
{
using (MyEntities db = new MyEntities())
{
//button was clicked. fetch all the check boxes from the rptFeesSession repeater into an int[]
}
}
There are several issues in your code (including conceptual / logic)
Item events in a Repeater should address item related things.
Click event handler has no access to CommandArgument attribute. Use Command instead.
Checkbox control doesn't support onclick event.
Checkbox events can run immediately only when there is AutoPostback="true".
If you want to refresh all repeater data on change of any checkbox then you can do something like this.
<asp:ScriptManager runat="server" ID="scriptMgr" /><%-- Strongly recommended --%>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Repeater ID="rptFeesSession" runat="server">
<HeaderTemplate>
<table>
</HeaderTemplate>
<ItemTemplate>
<asp:HiddenField ID="hdnIsSession" runat="server" Value='<%#Eval("isSession")%>' />
<tr runat="server" visible='<%# Eval("isSession")%>'>
<td colspan="2" style="position: relative;">
<asp:HyperLink CssClass="siteColorFG popBtn" ID="hlFeeType" runat="server" Text='<%#Eval("title")%>' NavigateUrl="javascript:;" />
</td>
<td>
<div class="">
<asp:HiddenField runat="server" ID="hidID" Value='<%#Eval("id") %>' />
<asp:CheckBox ID="LinkButton3"
AutoPostBack="true" CssClass="checkB"
OnCheckedChanged="LinkButton3_CheckedChanged" runat="server"
Text='<%#Eval("amount", "{0:C}")%>' />
</div>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
//.cs
protected void LinkButton3_CheckedChanged(object sender, EventArgs e)
{
decimal total = 0;
using (MyEntities db = new MyEntities())
{
foreach (RepeaterItem item in rptFeesSession.Items)
{
var chk = item.FindControl("LinkButton3") as CheckBox;
if(chk!=null && chk.Checked){
string id = (item.FindControl("hidID") as HiddenField).Value;
total += decimal.Parse(chk.Text);
//do stuff
}
}
}
}

how to multiline data comes from database

I'm retrieving an article from my db but it appears in a too long one line ! ,so I want to display it in a multiline way in my webpage
I'm using a datalist element to receive and show the data retrieved from db
articlesDL.DataSource = DS.select_all_articles();
articlesDL.DataBind();
and that's what my datalist appear in tags :
<asp:DataList ID="articlesDL" runat="server">
<ItemTemplate>
<table class="auto-style1">
<tr>
<td class="auto-style2">
<asp:ImageButton ID="ImageButton1" runat="server" Height="50px" ImageUrl='<%# "~/images/"+Eval("imageurl")+".jpg" %>' Width="50px" />
</td>
<td class="auto-style2">
<asp:LinkButton ID="LinkButton1" runat="server" PostBackUrl='<%# "~/reviewart.aspx?id="+Eval("articleid") %>' Text='<%# Eval("articlebody") %>'></asp:LinkButton>
</td>
</tr>
</table>
</ItemTemplate>
Try to set width to the panel where you are showing the data.
<div ID="articlesDL">
</div>
<style>
#articlesDL
{
width:100%;
}
</style>

Apply style to a <td> in repeater control

I need to apply style and highlight the header coloumn which is sorted..
Sorting is handled in rptMyTable_ItemCommand event.. i cant use gridview as the layout of displaying data is not a regular table.
in javascript we have something like
document.getElementById('lbCol1Header').parentNode.style = 'sortedColumnCSS'
how to do this in codebehind?
<table border="0" cellpadding="5" cellspacing="0" width="100%" class="myCSS">
<asp:Repeater ID="rptMyTable" runat="server" OnItemCommand="rptMyTable_ItemCommand">
<HeaderTemplate>
<tr style="font-weight: bolder">
<td>
<asp:LinkButton ID="lbCol1Header" Text="Col1" runat="server" CommandName="sortCol1" />
</td>
<td>
<asp:LinkButton ID="lbCol2Header" Text="Col2" runat="server" CommandName="sortCol2" />
</td>
<td>
<asp:LinkButton ID="lbCol3Header" Text="Col3" runat="server" CommandName="sortCol3" />
</td>
<td>
<asp:LinkButton ID="lbCol4Header" Text="Col4" runat="server" CommandName="sortCol4" />
</td>
<td>
<asp:LinkButton ID="lbCol5Header" Text="Col5" runat="server" CommandName="sortCol5" />
</td>
<td>
<asp:LinkButton ID="lbCol6Header" Text="Col6" runat="server" CommandName="sortCol6" />
</td>
<td>
</td>
<td>
</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
//Table Data......with nested tables and divs
.
.
.
.
.
</ItemTemplate>
</asp:Repeater>
<tr style="font-weight: bolder">
// doing paging operations here...
</tr>
</table>
In Design Page:
<tr class='<%# StyleSheet(DataBinder.Eval(Container.DataItem, "Y"))%>'>
for Linkbutton :
<asp:LinkButton ID="lbCol1Header" Text="Col1" runat="server" CommandName="sortCol1" CssClass='<%# StyleSheet(DataBinder.Eval(Container.DataItem, "Y"))%>' />
In code Page:
public static string StyleSheet(object objText1)
{
string val = string.Empty;
if (objText1.ToString() == "Y")
{
val = "trbind";
}
return val;
}
This is one of the way to apply style the in tr tag while in runtime based on the data.Similar you can try for the label also.
write the style trbind in stylesheet.
You could use .CssClass property in the rptMyTable_ItemCommand event I guess.
lbCol1Header.CssClass = "sortedColumnCSS";
If you want to apply the css class to you should give ID and add runat="server".
<td ID="tdCol1Header" runat="server">
<asp:LinkButton ID="lbCol1Header" Text="Col1" runat="server" CommandName="sortCol1" />
</td>
And to add the css class from your code behind.
tdCol1Header.Attributes("class") = "CssClass";

Firing an automatic update from DropDownList control within a ListView

I'm an asp.net newbie. Basically, I have a DropDownList within and EditItemTemplate within a ListView. When a new item is selected in the drop down, the user would like to NOT have to click the LinkButton for update, but have the update happen automatically. I've experimented with the OnSelectedIndexChanged="ddlrank_itemChanged" using code behind, as well as OnChange="MyFoo()" in javascript, but the details of what to do are beyound me.
I hope I am including the code sample correctly. Any suggestions will be greatly appreciated. Thanks.
<asp:ListView ID="ListView1" runat="server" DataKeyNames="rankingID" DataSourceID="SqlDataSource1" OnItemUpdated="ListView1_Item_Updated">
<LayoutTemplate>
<table cellpadding="2" width="640px" border="1" runat="server" id="tblRankings">
<tr id="Tr1" runat="server">
<th id="Th1" runat="server">Action</th>
<th id="Th3" runat="server">Rank</th>
<th id="Th4" runat="server">Committee name</th>
<th id="Th5" runat="server">Committee type</th>
</tr>
<tr runat="server" id="itemPlaceholder" />
</table>
<asp:DataPager runat="server" ID="RankingDataPager" PageSize="100">
<Fields>
<asp:NextPreviousPagerField ShowFirstPageButton="true" ShowLastPageButton="true"
FirstPageText="|<< " LastPageText=" >>|"
NextPageText=" > " PreviousPageText=" < " />
</Fields>
</asp:DataPager>
</LayoutTemplate>
<ItemTemplate >
<tr id="Tr2" runat="server">
<td>
<asp:LinkButton ID="EditButton" runat="Server" Text="Edit" CommandName="Edit" />
</td>
<td valign="top">
<asp:Label ID="RankLabel" runat="Server" Text='<%#Eval("rank") %>' />
</td>
<td valign="top">
<asp:Label ID="CommitteeNameLabel" runat="Server" Text='<%#Eval("committeename") %>' />
</td>
<td valign="top">
<asp:Label ID="CommitteeTypeLabel" runat="Server" Text='<%#Eval("committeetype") %>' />
</td>
</tr>
</ItemTemplate>
<EditItemTemplate >
<tr style="background-color: #ADD8E6">
<td>
<asp:LinkButton ID="UpdateButton" runat="server" CommandName="Update" Text="Update" />
<asp:LinkButton ID="CancelButton" runat="server" CommandName="Cancel" Text="Cancel" />
</td>
<td>
<asp:DropDownList ID="ddlrank"
DataSourceID="sdsrank"
DataValueField="vchvalue"
DataTextField="vchvalue"
OnSelectedIndexChanged="ddlrank_itemChanged"
OnChange="MyFoo()"
SelectedValue='<%# Bind("rank") %>' runat="server" >
</asp:DropDownList>
</td>
<td>
<asp:TextBox ID="CommitteeNameTextBox" runat="server" Enabled="false" ReadOnly="true" Text='<%#Bind("committeename") %>'
MaxLength="200" /><br />
</td>
<td>
<asp:TextBox ID="CommitteeTypeTextBox" runat="server" Enabled="false" ReadOnly="true" Text='<%#Bind("committeetype") %>'
MaxLength="20" /><br />
</td>
</tr>
</EditItemTemplate>
</asp:ListView>
I think you are missing AutoPostBack="true" on your dropdownlist property. Hope it helps.
You're headed in the right direction. You can use "OnSelectedIndexChanged", or you can create a function in your codebehind page that handles the SelectedIndexChanged event. Either way, when the user makes a selection from the dropdown, you get a postback and that function is executed. In the function you can do whatever you want. In a case like this that might mean checking what the selected value is and setting other values on the screen based on the new selection. When the function exits, a new screen is sent to the user's browser with any updated data.
Thanks for the replies, they helped direct and refine my internet searching!
I finally found a simple solution.
It just requires two lines of code in the OnSelectedIndexChanged code-behind function defined on the dropdownlist:
protected void ddlrank_itemChanged(object sender, EventArgs e)
{
ListViewDataItem item = (ListViewDataItem)((DropDownList)sender).Parent;
ListView1.UpdateItem(item.DisplayIndex, false);
}

How to use javascript validations for controls within ListView EditTemplate?

In Nridubai website,i am using listview EditTemplate for editing purpose. In my EditTemplate, there are controls like..
<asp:TextBox ID="txtEditEventName" runat="server"
Text='<%# Bind("event_name") %>' />
And a few more controls like dropdownlist, calender controls. Now I want to validate using javascript on these controls, but its not working.
Eg.
var eventStatus=document.getElementById("<%=txtEditEventName.ClientID%>").value;
I am not using validation controls. Please help me how to use javascript for validation on EditTemplate Controls? My EditTemplate structure is like the following:
<EditItemTemplate>
<td class="command"><asp:LinkButton ID="btnCancel" runat="server" Text="Cancel" CommandName="Cancel" />
<asp:LinkButton ID="LinkButton2" runat="server" Text="Update" CommandName="Update" />
</td>
<div class="header">View Details for '<%# Eval("event_name")%>'</div>
<tr>
<td class="edit" colspan="6" >
<div class="details">
<table class="detailview" cellpadding="0" cellspacing="0">
<tr>
<td>Event Name:</td>
<td>
<asp:TextBox ID="txtEditEventName" runat="server"
Text='<%# Bind("event_name") %>' />
</td>
<td>VenueAddress :</td>
<td>
<asp:TextBox ID="txtEditVenue" runat="server" Text='<%# Bind("venue") %>' />
</td>
</tr>
<tr>
<td>Country :</td>
<td>
<asp:DropDownList ID="lstEditCountry" runat="server"
Width="174" />
</td>
<td>Event Status:</td>
<td>
<asp:DropDownList ID="lstEditStatus" runat="server" Width="175px" >
<asp:ListItem value='0' Selected="True">-Select-</asp:ListItem>
<asp:ListItem >In-Progress</asp:ListItem>
<asp:ListItem >Completed</asp:ListItem>
<asp:ListItem >Aborted</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td>Category :</td>
<td>
<asp:DropDownList ID="lstEditCategory" runat="server"
Width="174" />
</td>
</tr>
<tr>
<td>Start Date:</td>
<td>
<asp:TextBox ID="txtEditStartDate" runat="server"
Text='<%# Bind("start_date", "{0:dd/MM/yyyy}") %>' />
</td>
<td>End Date:</td>
<td>
<asp:TextBox ID="txtEditEndDate" runat="server"
Text='<%# Bind("end_date","{0:dd/MM/yyyy}") %>' />
</td>
</tr>
</table>
<div class="footer command">
<asp:LinkButton ID="LinkButton1" runat="server" Text="Close" CommandName="Cancel" />
</div>
</div>
</td>
</tr>
</EditItemTemplate>
You can access the elements on ItemDataBound and emit their ClientIDs for your JavaScript to use:
ItemDataBound:
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
StringBuilder vars= new StringBuilder();
if (ListView1.EditItem != null)
{
TextBox txtEditStartDate = ListView1.EditItem.FindControl("txtEditStartDate") as TextBox;
TextBox txtEditEndDate = ListView1.EditItem.FindControl("txtEditEndDate") as TextBox;
//example js, however I recommend passing the ClientIDs to functions
vars.Append(String.Format("var txtEditStartDate='{0}';" txtEditStartDate.ClientID);
vars.Append(String.Format("var txtEditStartDate='{0}';", txtEditEndDate.ClientID );
ClientScriptManager.RegisterStartUpScript(this.GetType(), "validationVars", vars.ToString(), true);
}
}
***Old Answer, the .NET way************
EditTemplate:
<asp:TextBox ID="txtEditEventName" runat="server"
Text='<%# Bind("event_name") %>' />
<asp:RequiredFieldValidator
id="rfvEditEventName"
ClientValidationFunction="txtEditEventNameClientValidate"
ControlToValidate="txtTitle"
runat="server"
Display="dynamic">*
</asp:RequiredFieldValidator>
JS:
function txtEditEventNameClientValidate(sender, args) {
if (args.Value == '') {
args.IsValid = false; // field is empty
//so something
}
else {
//do something
}
}
Put the validation javascript in the EditTemplate itself. This way, when it switches to edit-mode, the control will be in the context.

Resources