Get the value of Label in listview - c#

I have a listview with invisible label to store the category Id.
what I want to do is to assign the text of the label to a cookie or session on button click.
the problem is my cookie is always null when I try to display the value outside the listview.
here is my aspx code:
<asp:ListView runat="server" ID="catListView" DataSourceID="CategoriesDataSource" >
<EmptyDataTemplate>No DataFound</EmptyDataTemplate>
<ItemTemplate>
<div class="service" style="margin-bottom:10px;width:230px;">
<h4 style="font-family:Corbel;" ><%#Eval("CatName") %></h4>
<asp:Label runat="server" Visible="false" ID="lblcat"><%#Eval("CatId") %></asp:Label>
<asp:Button runat="server" ID="btnTest" Text="View Items" OnClick="btnTest_Click" />
</div>
</ItemTemplate>
</asp:ListView>
my C# code:
protected void btnTest_Click(object sender, EventArgs e)
{
Response.Cookies["cat"].Value = "test";
foreach (ListViewItem item in catListView.Items)
{
Label catLabel = (Label)item.FindControl("lblcat");
Response.Cookies["cat"].Value = catLabel.Text.ToString();
}
}
any help will be appreciated.
thx in advance
Sam

It sounds like your ListView might not be databound when your Button click event is called.
I would recommend that you use the ItemCommand event handler. It is most appropriate for this type of handling. Update your ListView declaration to handle that event:
<asp:ListView runat="server" ID="catListView" DataSourceID="CategoriesDataSource
OnItemCommand="catListView_ItemCommand" >
Note: Don't forget to remove the "OnClick" event handler from the Button
And then write your even handler code like this:
protected void catListView_ItemCommand(object sender, ListViewCommandEventArgs e)
{
Label catLabel = (Label)e.Item.FindControl("lblcat");
Session["currentCatLabelText"] = catLabel.Text;
}
This also has the advantage of not looping through all your ListView items, but just looking at the one you clicked.

Hope this helps :)
string[] catvals = new string[catListView.Items.Count];
for (int i =0; i< catListView.Items.Count; i++)
{
Label catLabel = (Label)catListView.FindControl("lblcat");
catvals[i] = catLabel.Text;
}
for(int i = 0 ; i < catvals.Length; i++)
{
Response.Cookies["cat"+ i.ToString()].Value = catvals[i].ToString();
}

Actually you are trying to add your cat in one key. I mean you are overwriting values in loop.
You should change your code in this way:
In your C# code:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
HttpCookie testCokkie = new HttpCookie("ExampleCookie");
testCokkie.Expires = DateTime.Now.AddDays(5);
Response.Cookies.Add(testCokkie);
}
}
protected void btnTest_Click(object sender, EventArgs e)
{
HttpCookie ExampleCookie = Request.Cookies["ExampleCookie"];
int tempIndex = 0;
foreach (ListViewItem item in catListView.Items)
{
Label catLabel = (Label)item.FindControl("lblcat");
ExampleCookie["cat" + tempIndex.ToString()] = catLabel.Text.ToString();
tempIndex = tempIndex + 1;
}
}
TO read this cookie
HttpCookie exampleCookie = Request.Cookies["ExampleCookie"];
if (exampleCookie != null)
{
int tempIndex = 0;
foreach (ListViewItem item in catListView.Items)
{
Response.Write("<br/>" + exampleCookie["cat" + tempIndex.ToString()]);
tempIndex = tempIndex + 1;
}
}

Related

Button Inside a grid value is not returning updated value onclick event

I have a Button inside an ItemTemplate in a grid. I'm assigning the button text dynamically. Since I need to have different text for each row button. But OnClick event is not showing the updated text instead it is showing a empty string. Please help!!
<asp:TemplateField HeaderText="GetHistory">
<ItemTemplate>
<asp:Button
DataField="GetHistory"
ID="btn_getHistory"
CausesValidation="false"
runat="server"
OnClick="btn_getHistory_Click" Visible="false" />
</ItemTemplate>
</asp:TemplateField>
protected void btn_getHistory_Click(object sender, EventArgs e)
{
//My sender text is showing empty here
}
protected void GridViewTree1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.DataItem != null && !((System.Data.DataRowView)(e.Row.DataItem)).Row.ItemArray[0].ToString().Contains("\\"))
{
Button btn_getHistory = (Button)e.Row.Cells[3].FindControl("btn_getHistory");
if (btn_getHistory != null)
{
btn_getHistory.Visible = true;
var chunks = ((System.Data.DataRowView)(e.Row.DataItem)).Row.ItemArray[0].ToString().Split('_'); // any separator characters
var a = chunks.Take(chunks.Length - 1);
string testsetName = string.Empty;
foreach (string b in a)
{
testsetName = testsetName + b + '_';
}
btn_getHistory.Text = testsetName.ToString().TrimEnd('_');
}
}

How to enable button based on gridview value?

I have a column in SQL:
Status
open
Close
and Gridview with Boundfield value='Status'
When a user selects a row and the Status == open then it should display a button. Otherwise ist hiden.
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
string y = Data.Rows[GridView1.SelectedIndex][5].ToString();
if (y == "open")
{
btnAccept.Visible = true;
}
else
{
btnAccept.Visible = false;
}
}
<asp:Button Text="Accept" OnClick="btnAccept_Click" Visible="false" ID="btnAccept" runat="server" />
This could be the solution:
string y = GriView1.SelecteRows[0].Cells[5].Value.ToString();
Modify your code like this
string y = GridView1.SelectedRow.Cells[5].Text;
It's counter-intuitive, but GridView1.SelectedRow is not set until after SelectedIndexChanged completes.
Also visibility has nothing to do with the button being Enabled or Disabled.
Use the Enabled Property of the Button:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridView gv = (GridView) sender ;
btnAccept.Enabled = (gv.Rows[ gv.SelectedIndex ].Cells[5].Text == "open");
}
Also, if you haven't already, consider styling disabled buttons with CSS:
input[type=button][disabled],
button[disabled]
{
cursor:not-allowed;
}

connect asp repeaters with objects outside repeaters

I have a dropdown in my repeater.. i want to copy its value to textbox that is outside repeaters..
here is what I want to do
copy value from dropdown[1] to textbox1
copy value from dropdown[2] to textbox2 and so on...
here is my code
ASP:
<asp:DropDownList ID="fmFrom" runat="server" Height="20px" Width="120px" DataSourceID="BrDatasource" DataTextField="branchName" DataValueField="branchCode" AutoPostBack="true" onselectedindexchanged="fmFrom_SelectedIndexChanged"></asp:DropDownList>
c#:
protected void fmFrom_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i < rateRepeater.Items.Count; i++)
{
DropDownList from = (DropDownList)rateRepeater.Items[i].FindControl("fmFrom");
TextBox1.Text = from.SelectedValue.ToString();
}
}
here all my textbox gets the value of the last dropdown only...
what should I do?
Try:
protected void fmFrom_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i < rateRepeater.Items.Count; i++)
{
DropDownList from = (DropDownList)rateRepeater.Items[i].FindControl("fmFrom");
((TextBox)FindControl("TextBox" + (i + 1))).Text = from.SelectedValue.ToString();
}
}
change this:
TextBox1.Text = from.SelectedValue.ToString();
to:
TextBox1.Text += from.SelectedValue.ToString();

How to pass dropdownlist value to another page

I have a DropDownList with button:
<form id="form1" runat="server">
<asp:DropDownList ID="DropDay" runat="server"/>
<input type="submit" value="Save" runat="server" id="btn"/>
</form>
C# code for the page:
protected void Page_Load(object sender, EventArgs e)
{
btn.ServerClick+=new EventHandler(btn_ServerClick);
}
void btn_ServerClick(object sender, EventArgs e)
{
HttpContext value= HttpContext.Current;
value.Items.Add("Day", DropDay.SelectedValue);
Server.Transfer("ASP_2.aspx");
}
In ASP_2 I have a label, that I need to set the selected Dropdownlist value. And here is the code for ASP_2.aspx:
protected void Page_Load(object sender, EventArgs e)
{
HttpContext value= HttpContext.Current;
lblDay.Text = value.Items["Day"].ToString();
}
The problem is, that the value always is the first item from the dropdown. How do I set the selected value?
EDIT
the way I am filling the dropdown list The code goes in Page_Load:
DropDay.Items.Clear();
for (int i = 1; i <= 10; i++)
{
DropDay.Items.Add(i.ToString());
}
Your code for filling the DDL should be (at least) :
if (!IsPostBack)
{
DropDay.Items.Clear();
for (int i = 1; i <= 10; i++)
{
DropDay.Items.Add(i.ToString());
}
}
Hope this will help
You can use this in first page:
Server.Transfer("ASP_2.aspx?dropdown="+DropDay.SelectedValue);
and in the second page
protected void Page_Load(object sender, EventArgs e)
{
string val=Request.QueryString["dropdown"].toString();
}
Maybe you left the autopostback property of the dropdownlist true.
Figured out it by myself, just needed to remove "DropDay.Items.Clear();"
//DropDay.Items.Clear(); removed this line and the thing was fixed
for (int i = 1; i <= 10; i++)
{
DropDay.Items.Add(i.ToString());
}
Have you tried DropDay.SelectedItem.Text?

asp.net auto generated textboxes ID on webform

I am using C# on Visual Studio. I want to generate a webform with auto numbered Textboxes depending on the input from the previous page. What is the best way to do this loop?
For example:
Input is 4
The next page should generate textboxes with ID of
"name1"
"name2"
"name3"
"name4"
Something like this :
<asp:TextBox ID="name1" runat="server"></asp:TextBox>
<asp:TextBox ID="name2" runat="server"></asp:TextBox>
<asp:TextBox ID="name3" runat="server"></asp:TextBox>
<asp:TextBox ID="name4" runat="server"></asp:TextBox>
Part 2 of my question is that if I want to call them when a Button is click, how should I use a loop the get those ID?
Use for loop and PlaceHolder control to create dynamic TextBox controls
<asp:PlaceHolder ID="phDynamicTextBox" runat="server" />
int inputFromPreviousPost = 4;
for(int i = 1; i <= inputFromPreviousPost; i++)
{
TextBox t = new TextBox();
t.ID = "name" + i.ToString();
}
//on button click retrieve controls inside placeholder control
protected void Button_Click(object sender, EventArgs e)
{
foreach(Control c in phDynamicTextBox.Controls)
{
try
{
TextBox t = (TextBox)c;
// gets textbox ID property
Response.Write(t.ID);
}
catch
{
}
}
}
You could create those controls in the Page Init event handler by say loop for the number of times the control needs to made available.
Please remember since these are dynamic controls they need to be recreated during postbacks and will not be done automatically.
Further Dynamic controls and postback
Check this code.
In first page...
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx?Name=" + TextBox1.Text);
}
In second page you can get the value from querystring and create controls dynamically
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["Name"] != null)
Response.Write(Request.QueryString["Name"]);
Int32 howmany = Int32.Parse(Request.QueryString["Name"]);
for (int i = 1; i < howmany + 1; i++)
{
TextBox tb = new TextBox();
tb.ID = "name" + i;
form1.Controls.Add(tb);
}
}
for ( int i=0; i<4; i++ )
{
TextBox t = new TextBox();
t.ID = "name" + i.ToString();
this.Controls.Add( t );
}

Categories