Place session variable value in the Text of label in asp.net - c#

I have some labels inside a DataList which are populated with text from as the DataList is binded with database. Now i want to place the value of Text of asp.net with Session variable.
<asp:DataList ID = "dl_cmt" runat="server">
<ItemStyle CssClass="coment" />
ItemTemplate>
<asp:Label ID="ll" runat="server" Text='<%# %>' />
<asp:Label ID="lblcmt" runat="server" Text='<%#Eval("ecomment")%>' />
<asp:Label ID="lblDate" style=" color:brown; font-family:Cursive; font-size:x-small; " runat="server" Text='<%#Eval("my_date","on {0}") %>' />
</ItemTemplate>
</asp:DataList>
I want to place the text of label ID="ll" with session["userid"]

You can get the value as follows
ll.Text = Session["userid"].ToString();
Another approach:
You can also hide the implementation details from the aspx code with a property
.cs file
public string userid { get { return Session["userid"]; } }
.aspx file
<asp:Label ID="ll" runat="server" Text='<%= userid %>' >

This will work.
<asp:Label ID="ll" runat="server" Text='<%#Session["yourvariable"]%>'/>

Related

how to change label to textbox in gridview on checkbox click using JQuery

I got a gridview where checkboxes are displayed for each and every row. Upon clicking the checkbox the alternate names label should change to textbox with the content in it remaining as it is.
If the user unchecks the checkbox the textbox should again revert back to label.
How can I achieve this in Jquery.
The code behind code is as follows:
<asp:GridView ID="GridView1" runat="server" OnRowUpdating="GridView1_RowUpdating" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="checkbox1" runat="server" OnClick="checkboxing()" />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="checkbox1" runat="server" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City Name Id">
<ItemTemplate>
<asp:Label ID="NameId" runat="server" Text='<%# Eval("Name_Id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="CityName" runat="server" Text='<%# Eval("name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Geo Name">
<ItemTemplate>
<asp:Label ID="GeoName" runat="server" Text='<%# Eval("geoname") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Ascii Name">
<ItemTemplate>
<asp:Label ID="AsciiName" runat="server" Text='<%# Eval("asciiname") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Alternate Names" SortExpression="AlternateNames">
<EditItemTemplate>
<asp:Label ID="AlternateNames" runat="server" Text='<%# Eval("alternateNames") %>'>
</asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="AlternateNames" runat="server" Text='<%# Eval("alternateNames") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Longitude">
<ItemTemplate>
<asp:Label ID="Longitude" runat="server" Text='<%# Eval("longitude") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Latitude">
<ItemTemplate>
<asp:Label ID="Latitude" runat="server" Text='<%# Eval("latitude") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The Javascript that executes on checking/unchecking the checkbox is the following one:
function checkboxing() {
alert("im here in checkboxing");
$("input:checkbox").click(function () {
if ($(this).is(":checked")) {
alert("This is so true ");
}
else {
alert("false");
}
});
}
Now my intention is
To change the alternate names - Label to Textbox with contents in it remaining as it is for the user to edit,
If the user unchecks the checkbox later, the contents should revert with textbox again changing to Label.
How can achieve this using JQuery
there are two ways to achieve it
1 dynamically create elements on each checkbox click
2 create both label and textbox but hide them on the basis of checkbox event
since you are using strongly typed views the second one should be the better option
if you use the client side input elements you could have dynamically append the element on the basis of click function.
now i would recommend the 2nd method instead of the 1st one because the 2nd one will manipulate the dom which in your case is not a necessity where as the 2nd option will only add a hidden class to your element which is less complex and also a better in terms of performance
The name should be input instead of label, use class each row item instead of id.
Suggestion : from input:checked find the parent row and find name
Demo
you can change the DOM from label to input field
Upon toggling the checkbox, you can enable/disable.
You can also set custom styles to the disabled input field like as if its a label.
Hope the idea is of any help
Try Below. I am assuming you are trying to edit the last row and you have only one checkbox each row.
$(document).ready(function () {
$("table input[type=checkbox]").on("change", function (event) {
var obj = $(event.target);
var tr = $(obj).closest("tr");
var td = $(tr).find("td:last");
if ($(obj).is(":checked")) {
var data = $(td).find("span").html();
$(td).html("<input id=none value=" + data + " />");
}
else {
var data = $(td).find("input").val();
$(td).html("<span >"+data+"</span>" );
}
});
});
Try the below codes
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
function toggleControl(chk)
{
var cell = $(chk).parent();
var lbl = $(cell).siblings().find('#lblNames');
var txtbx = $(cell).siblings().find('#txtNames');
var str;
if($(chk).is(':checked'))
{
str = $(lbl).text();
$(lbl).hide();
$(txtbx).val(str);
$(txtbx).show();
}
else {
$(lbl).show();
$(txtbx).hide();
}
}
</script>
<asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="checkbox1" runat="server" OnClick="toggleControl(this)" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Alternate Names">
<ItemTemplate>
<asp:Label ID="lblNames" ClientIDMode="Static" runat="server" Text='Hello World!'>
</asp:Label>
<input type="text" id="txtNames" style="display:none;" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Default.aspx.cs file codes:
namespace aspnetWeb
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<Student> list = new List<Student>();
for(int i=1;i<=10;i++)
list.Add(new Student { ID = 1, Count = 20 });
GridView1.DataSource = list.AsQueryable();
GridView1.DataBind();
}
}
public class Student
{
public int ID { get; set; }
public int Count { get; set; }
}
}

How can i use If condition in aspx page for image url?

My dataset return this table link.How can i use If else conditons in aspx page?I want if the File_path is Null or empty then image not show because if File_Path is empty then it give me error,I want if File_Path is not empty then image will be show.Following error
Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.
Here is my code
<asp:DataList ID="DataList2" runat="server" Font-Bold="False" Font-Italic="False" Font-Overline="False" Font-Strikeout="False" Font-Underline="False" HorizontalAlign="Center" RepeatLayout="Table">
<ItemTemplate>
<div class="<%#GetStyleForMsgList(Eval("MsgSender").ToString()) %> MainChatListClass">
<asp:Label ID="Label1" runat="server" Text='<%# GetPerfactName(Eval("MsgSender").ToString()) %>'></asp:Label>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("ChatMsg") %>'></asp:Label>
<asp:Label ID="lblfile" runat="server" Visible ="false" Text='<%# Eval("File_Path") %>'></asp:Label>
<% if (Eval("File_Path") != null)
{%>
<asp:Image ID ="img" runat ="server" ImageUrl ='<%# Eval("File_Path") %>' />
<% } %>
</div>
</ItemTemplate>
</asp:DataList>

Change List Colour according to date

I have a DataList which I am binding on load, which works perfectly fine. My question is how do I make this to show records that don't have a date in database, in different text colour? here is my code:
<asp:DataList ID="dlS" runat="server" EnableViewState="false">
<ItemTemplate>
<asp:Label ID="Label" runat="server" Text='<%# Eval("Name") %>' /><br />
</ItemTemplate>
</asp:DataList>
Guid ID = (Guid)Session["ID"];
lstL = Manager.Get_ByID(ID);
if (lstLetters != null)
{
dlS.DataSource = lstL;
dlS.DataBind();
}
I'm not sure what you really mean by "records that don't have a date in database",
but if it means that those records have NULL value as date then you can rewrite the Label as below:
<asp:Label ID="Label" runat="server" Text='<%# Eval("Name") %>' ForeColor='<%# Eval("DateValue") == System.DBNull ? System.Drawing.Color.Red : System.Drawing.Color.Blue %>' />

How to get the clientid of the control which is placed inside the Edit item template of the gridview in javascript

i to get the clientid of the control which is placed inside the Edit item template of the gridview in javascript without going to the server side code..
<asp:TemplateField HeaderText="FromDate" SortExpression="FromDate">
<ItemTemplate>
<asp:Label ID="FromDate" runat="server" Text='<%#((DateTime)DataBinder.Eval(Container.DataItem,"FromDate")).ToShortDateString()%>'></asp:Label>
<asp:HiddenField ID="ID" runat="server" Value='<%#Eval("ID") %>' />
<asp:HiddenField ID="ApproveLeaveID" runat="server" Value='<%#Eval("ApproveLeaveID") %>' />
<asp:HiddenField ID="hidLevel3" runat="server" Value='<%#Eval("Level3ManagerACENumber") %>' />
</ItemTemplate>
<EditItemTemplate>
<table>
<tr>
<td>
<asp:TextBox ID="txtFDate" runat="server" Text='<%#((DateTime)DataBinder.Eval(Container.DataItem,"FromDate")).ToShortDateString()%>'>
</asp:TextBox>
<asp:HiddenField ID="ID" runat="server" Value='<%#Eval("ID") %>' />
<asp:HiddenField ID="ApproveLeaveID" runat="server" Value='<%#Eval("ApproveLeaveID") %>' />
<asp:HiddenField ID="hidLevel3" runat="server" Value='<%#Eval("Level3ManagerACENumber") %>' />
</td>
<td>
<a onclick="showCalendarControl(3,<%# Container.ItemIndex %>)">
<img id="img3" runat="server" alt="Clock" src="../Images/clock_add.png" style="border: none" /></a>
</td>
</tr>
</table>
</EditItemTemplate>
<ItemStyle HorizontalAlign="Left" />
<HeaderStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="ToDate" SortExpression="ToDate">
<ItemTemplate>
<asp:Label ID="ToDate" runat="server" Text='<%#((DateTime)DataBinder.Eval(Container.DataItem,"ToDate")).ToShortDateString()%>'>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<table>
<tr>
<td>
<asp:TextBox ID="txtTDate" runat="server" Text='<%#((DateTime)DataBinder.Eval(Container.DataItem,"ToDate")).ToShortDateString()%>'>
</asp:TextBox>
</td>
<td>
<a onclick="showCalendarControl(4,<%# Container.ItemIndex %>)">
<img id="img4" runat="server" alt="Clock" src="../Images/clock_add.png" style="border: none" /></a>
</td>
</tr>
</table>
</EditItemTemplate>
<ItemStyle HorizontalAlign="Left" />
<HeaderStyle HorizontalAlign="Center" />
</asp:TemplateField>
This is my java script:
function showCalendarControl(ControlNo,index) {
var textField;
if(ControlNo==1)
{
textField=document.getElementById('<%=txtFromDate.ClientID%>');
}
else
{
textField=document.getElementById('<%=txtToDate.ClientID%>');
}
if(ControlNo==3)
{
textField=document.getElementsByClassName('txtFDate')[index];
}
if(ControlNo==4)
{
textField=document.getElementsByClassName('txtTDate')[index];
}
calendarControl.show(textField);
}
first two textbox(txtFromDate,txtToDate) is for the not in the grid control...
You can fetch the elements in the ItemDataBound event of the grid (using FindControl), and then pass the ClientID of the textbox as a parameter to showCalendarControl:
TextBox txtFDate = e.Item.FindControl("txtFDate") as TextBox;
TextBox txtTDate = e.Item.FindControl("txtTDate") as TextBox;
HtmlAnchor link = e.Item.FindControl("aLink") as HtmlAnchor;
if (txtTDate != null && txtFDate != null && link != null)
{
link.Attributes.Add("onclick", String.Format("showCalendarControl({0}, '{1}', '{2}')", 4, txtFDate.ClientID, txtTDate.ClientID);
}
(you'll also need to add an ID and a runat="server" to your link. I'm also assuming txtFDate is declared in your EditTemplate although it's not there. The ControlNo parameter could be a data key instead of a constant as in the example, it's not really clear what it is)
Then, in your function, use the clientID parameters to get the textboxes:
function showCalendarControl(ControlNo, txtFDateClientID, txtTDateClientID) {
var textField;
if(ControlNo==3)
{
textField=document.getElementById(txtFDateClientID);
}
if(ControlNo==4)
{
textField=document.getElementById(txtTDateClientID);
}
calendarControl.show(textField);
}
The problem is that every control should have unique server ID. So server side controls which are placed inside template are rendered multiple times with different auto generated ids based on ID you've specified in the template. You can easily see it if you will have a look on the generated html. Therefore your js code is accessing only the html element with hardcoded id. As I guess it is placed in the first row.
Simple solution is to describe your text box in a following way
<asp:TextBox ID="txtTDate" runat="server" CssClass="txtTDate" Text='<%#((DateTime)DataBinder.Eval(Container.DataItem,"ToDate")).ToShortDateString()%>'>
</asp:TextBox>
Then modify the js function in the following way :
function showCalendarControl(ControlNo, index) {
var textField;
if(ControlNo==3)
{
textField=document.getElementsByClassName('txtFDate')[index];
}
if(ControlNo==4)
{
textField=document.getElementsByClassName('txtTDate')[index];
}
calendarControl.show(textField);
}
And modify your link as the following :
<a onclick="showCalendarControl(4, <%# Container.DataItemIndex %>)">
Updated the answer
DataItemContainer has DataItemIndex property which has to be used in this case.

How to use button in repeater control?

I am using asp.net 3.5 with c#.I want to invoke button click event inside repeater control.
<asp:Repeater ID="rptFriendsList"
runat="server"
onitemcommand="rptFriendsList_ItemCommand">
<ItemTemplate>
<asp:ImageButton ID="btnSave"
runat="server"
ImageUrl="~/Contents/Images/save_button.png"
CommandName="Schedule"
UseSubmitBehavior="False" />
</ItemTemplate>
</asp:Repeater>
but when i click to a button its giving an error
"Invalid postback or callback
argument. Event validation is enabled
using in
configuration or <%# Page
EnableEventValidation="true" %> in a
page. For security purposes, this
feature verifies that arguments to
postback or callback events originate
from the server control that
originally rendered them. If the data
is valid and expected, use the
ClientScriptManager.RegisterForEventValidation
method in order to register the
postback or callback data for
validation."
my purpose is to execute some code in button click which is placed inside the repeater.Please help me to solve this issue.Thanks in advance.
UseSubmitBehavior="False" this property you have used is not present with the image button have you over ridden imagebutton class and added this property.
<asp:Repeater ID="Repeater1" runat="server" OnItemCommand="Repeater1_OnItemCommand" DataSourceID="SqlDataSource1">
<ItemTemplate>
key1:
<asp:Label ID="key1Label" runat="server" Text='<%# Eval("key1") %>'></asp:Label><br />
key2:
<asp:Label ID="key2Label" runat="server" Text='<%# Eval("key2") %>'></asp:Label><br />
key3:
<asp:Label ID="key3Label" runat="server" Text='<%# Eval("key3") %>'></asp:Label><br />
<asp:TextBox ID="col1" runat="server" Text='<%# Eval("col1") %>'></asp:TextBox>
<asp:TextBox ID="col2" runat="server" Text='<%# Eval("col2") %>'></asp:TextBox>
<br />
<asp:linkbutton ID="Linkbutton1" commandname="Update" runat="server" text="Update" CommandArgument='<%# Eval("key1") +"|"+Eval("key2")+"|"+ Eval("key3") %>' />
<asp:linkbutton ID="Linkbutton2" commandname="Cancel" runat="server" text="Cancel" />
</ItemTemplate>
protected void Repeater1_OnItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "Update")
{
string col1 = ((TextBox)e.Item.FindControl("col1")).Text;
string col2 = ((TextBox)e.Item.FindControl("col2")).Text;
string allKeys = Convert.ToString(e.CommandArgument);
string[] arrKeys = new string[2];
char[] splitter = { '|' };
arrKeys = allKeys.Split(splitter);
SqlDataSource1.UpdateParameters["col1"].DefaultValue = col1;
SqlDataSource1.UpdateParameters["col2"].DefaultValue = col2;
SqlDataSource1.UpdateParameters["key1"].DefaultValue = arrKeys[0];
SqlDataSource1.UpdateParameters["key2"].DefaultValue = arrKeys[1];
SqlDataSource1.UpdateParameters["key3"].DefaultValue = arrKeys[2];
SqlDataSource1.Update();
Repeater1.DataBind();
}
}
This also happens when you have assigned the datasource and data bound your repeater in the OnLoad event rather than OnInit
I have used this bellow code and runs ok
use this bellow code in .aspx page
<asp:Repeater ID="Repeater1" runat="server" OnItemCommand="Repeater1_ItemCommand">
<HeaderTemplate>
<table>
<tr>
<th>
Edit
</th>
</tr>
</table>
</HeaderTemplate>
<ItemTemplate>
<table>
<tr>
<td align="center">
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Edit">Edit</asp:LinkButton>
</td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
Use this in .cs Make the event Repeater1_ItemCommand
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
switch (e.CommandName)
{
case "Edit":
// Do some stuff when the Edit button is clicked.
break;
// Other commands here.
default:
break;
}
}
You can't use button, because button create postback on click and also itemcommand of repeater called!
But, If you want to use asp:button instead of asp:linkbutton, you have to set UseSubmitBehavior property of button to false. its means, button dont make postback.
<asp:Button ID="btnAccept" runat="server" Text="Accept All" CssClass="vb-default vb-green vb-txt-light" CommandName="Accept" CommandArgument='<%# Eval("UserID") %>' UseSubmitBehavior="false" />
Set page EnableEventValidation="false".
if you're adding items server side, try to assign unique ID to each ImageButton

Categories

Resources