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;
}
Related
I want to blink selected rows in gridview. I'm using a jquery and binding it to ID attribute under RowDataBound method.
But only one row (first one) is blinking, even if there are multiple rows set to blink.
Here is the HTML body
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager" runat="server" />
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<fieldset>
<div>
<asp:GridView ID="GrdScreen1" runat="server" OnRowDataBound="GrdTaskDetail_RowDataBound" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Shift">
<ItemTemplate>
<asp:Label ID="testblinklbl" runat="server" Text='<%# Eval("Shift") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="TaskName">
<ItemTemplate>
<asp:Label ID="testemplbl" runat="server" Text='<%# Eval("TaskName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="IsBlinkON">
<ItemTemplate>
<asp:Label ID="testblklbl" runat="server" Text='<%# Eval("ToBlink") %>'></asp:Label>
<asp:HiddenField ID="hddblink" runat="server" Value='<%#Eval("ToBlink")%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
Here is the script
<script type="text/javascript">
$(function() {
blinkeffect('#txtblnk');
})
function blinkeffect(selector) {
$(selector).fadeOut('slow', function() {
$(this).fadeIn('slow', function() {
blinkeffect(this);
});
});
}
</script>
Here is my Rowdatabound and on page load code -
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable dt = new DataTable();
dt = Heatcon.GetAuxcabOpDashboardScreen1("Station 1");
if (dt.Rows.Count > 0)
{
GrdScreen1.DataSource = dt;
GrdScreen1.DataBind();
}
}
}
protected void GrdTaskDetail_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HiddenField BlinkTask = (e.Row.FindControl("hddblink") as HiddenField);
if (BlinkTask.Value.ToString() == "1")
{
e.Row.Attributes.Add("id", "txtblnk");
}
}
}
This is working but only for one row (first one). I tried debugging to see if blinkvalue for other rows is getting set to "1" and it is.
Please let me know if there is something I'm missing? not sure if issue with asp gridview or jquery.
Thanks in advance!
I can provide additional details if required.
Your code is not working because you are using same "id" attribute value for more than one control. "id" value is unique for each control in page.
In order to make this work you will have to use "class" attribute. Try following changes.
<script type="text/javascript">
$(function() {
blinkeffect('.clstxtblnk');
})
function blinkeffect(selector) {
$(selector).fadeOut('slow', function() {
$(this).fadeIn('slow', function() {
blinkeffect(this);
});
});
}
</script>
Make changes to RowDataBound method to add "class" attribute instead of "id" attribute.
protected void GrdTaskDetail_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HiddenField BlinkTask = (e.Row.FindControl("hddblink") as HiddenField);
if (BlinkTask.Value.ToString() == "1")
{
e.Row.Attributes.Add("class", "clstxtblnk");
}
}
}
Actually i am trying to redirect command argument of a button present in a data list to another page. I am using Request.QueryString method to access the command argument on another page with the help of command name of the button. Please help me with it...
this is code of button present inside Data List
<asp:Button ID="Button1" runat="server" Text="Read" CommandArgument='<%# Eval("id")%>' OnClick="Button1_Click" CommandName="content"/>
this is code present in DataList Item command function
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
Response.Redirect("content.aspx?content=" +e.CommandArgument.ToString());
}
this is the onclick function code
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("content.aspx");
}
this is the code on another page(content.aspx)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
String id = Request.QueryString["content"];
Label1.Text = id;
}
}
this is entire datalist code
<asp:DataList ID="DataList1" runat="server" DataKeyField="Id" DataSourceID="SqlDataSource1" Height="657px" RepeatColumns="4" RepeatDirection="Horizontal" Width="1248px" OnItemCommand="DataList1_ItemCommand" OnItemDataBound="DataList1_ItemDataBound">
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<ItemStyle ForeColor="#000066" />
<ItemTemplate>
<table class="auto-style2">
<tr>
<td style="text-align: center">
<asp:Label ID="Label2" runat="server" Text='<%# Eval("name") %>'></asp:Label>
<asp:Label ID="Label4" runat="server" Text='<%# Eval("Id") %>' Visible="False"></asp:Label>
</td>
</tr>
<tr>
<td style="text-align: center">
<asp:Image ID="Image2" runat="server" Height="250px" ImageUrl='<%# Eval("image") %>' Width="250px" />
</td>
</tr>
<tr>
<td style="text-align: center">
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
<br />
<asp:ImageButton ID="ImageButton1" runat="server" CommandName="addtofav" CommandArgument='<%# Eval("id")%>' Height="30px" Width="20px" />
</td>
</tr>
<tr>
<td style="text-align: center">
<asp:Button ID="Button1" runat="server" Text="Read" CommandArgument='<%# Eval("id")%>' OnClick="Button1_Click" CommandName="content"/>
</td>
</tr>
</table
<br />
<br />
</ItemTemplate>
<SelectedItemStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
it does redirect to another page(content.aspx) but the label does not show the querystring text.
Try updating the DataList1_ItemCommand event to this:
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "content")
{
Response.Redirect("content.aspx?content=" +e.CommandArgument.ToString());
}
}
also make sure you are checking IsPostBack in Page_Load method of this page code behind.
Yes i got the desired output. Actually i was also using another button to redirect to a diiferent page in DataList1_ItemCommand function. So i just needed to seperate the Response.redirects of the 2 buttons by putting them in if loop.
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "content")
{
Response.Redirect("content.aspx?content="+e.CommandArgument.ToString());
}
if (e.CommandName == "addtofav")
{
Response.Redirect("sortbyAZ.aspx?addtofav=" + e.CommandArgument.ToString());
}
}
Thanks You everybody for helping me out with this one
I think you are not casting the Request.QueryString["content"] to string format, try this
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
String id = Request.QueryString["content"];
Label1.Text = id;
}
}
You can find all information you need in this tutorial. from #microsoft msdn
Best of luck
<%# Page Language="C#" AutoEventWireup="True" %>
<%# Import Namespace="System.Data" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>DataList Select Example</title>
<script runat="server">
ICollection CreateDataSource()
{
// Create sample data for the DataList control.
DataTable dt = new DataTable();
DataRow dr;
// Define the columns of the table.
dt.Columns.Add(new DataColumn("Item", typeof(Int32)));
dt.Columns.Add(new DataColumn("Qty", typeof(Int32)));
dt.Columns.Add(new DataColumn("Price", typeof(double)));
// Populate the table with sample values.
for (int i = 0; i < 9; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = i * 2;
dr[2] = 1.23 * (i + 1);
dt.Rows.Add(dr);
}
DataView dv = new DataView(dt);
return dv;
}
void Page_Load(Object sender, EventArgs e)
{
// Load sample data only once, when the page is first loaded.
if (!IsPostBack)
{
ItemsList.DataSource = CreateDataSource();
ItemsList.DataBind();
}
}
void Item_Command(Object sender, DataListCommandEventArgs e)
{
// Set the SelectedIndex property to select an item in the DataList.
ItemsList.SelectedIndex = e.Item.ItemIndex;
// Rebind the data source to the DataList to refresh the control.
ItemsList.DataSource = CreateDataSource();
ItemsList.DataBind();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<h3>DataList Select Example</h3>
Click <b>Select</b> to select an item.
<br /><br />
<asp:DataList id="ItemsList"
GridLines="Both"
CellPadding="3"
CellSpacing="0"
OnItemCommand="Item_Command"
runat="server">
<HeaderStyle BackColor="#aaaadd">
</HeaderStyle>
<AlternatingItemStyle BackColor="Gainsboro">
</AlternatingItemStyle>
<SelectedItemStyle BackColor="Yellow">
</SelectedItemStyle>
<HeaderTemplate>
Items
</HeaderTemplate>
<ItemTemplate>
<asp:LinkButton id="SelectButton"
Text="Select"
CommandName="Select"
runat="server"/>
Item <%# DataBinder.Eval(Container.DataItem, "Item") %>
</ItemTemplate>
<SelectedItemTemplate>
Item:
<asp:Label id="ItemLabel"
Text='<%# DataBinder.Eval(Container.DataItem, "Item") %>'
runat="server"/>
<br />
Quantity:
<asp:Label id="QtyLabel"
Text='<%# DataBinder.Eval(Container.DataItem, "Qty") %>'
runat="server"/>
<br />
Price:
<asp:Label id="PriceLabel"
Text='<%# DataBinder.Eval(Container.DataItem, "Price", "{0:c}")
%>'
runat="server"/>
</SelectedItemTemplate>
</asp:DataList>
</form>
</body>
</html>
By the way I think you don't need define Button Click event. Already defined path with variable. Just convert button to Link Button and remove Button Click Event
I want to grab the selected value from the DropDownLists in my DataGrid when a submit button is clicked, but they always return the first option in the dropdown (approve). How can I get the selected value when using static dropdown items like this?
.aspx code:
<!-- several BoundColumns were here -->
<asp:TemplateColumn HeaderText="Actions">
<HeaderStyle CssClass="ProfDataGridHeader" BorderStyle="Solid" BorderWidth="1"></HeaderStyle>
<ItemStyle Width="45%" CssClass="ProfDataGridRow" BorderStyle="Solid" BorderWidth="1"></ItemStyle>
<ItemTemplate>
<asp:DropDownList ID="ddlApprovalStatus" AppendDataBoundItems="True" runat="server" Width="150px" EnableViewState="true" ViewStateMode="Enabled">
<asp:ListItem Value="approve" Text="Approve"></asp:ListItem>
<asp:ListItem Value="reject" Text="Reject"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
<br />
<asp:Button ID="btnSubmit" Text="Submit" runat="server" CssClass="ally-btn" OnClick="btnSubmit_Click" />
.aspx.cs code:
protected void btnSubmit_Click(object sender, EventArgs e)
{
DropDownList DDLP;
string acceptStatus;
debugLabel.Text = "";
for (int i = 0; i < dgApprovals.Items.Count; i++)
{
DDLP = (DropDownList)dgApprovals.Items[i].FindControl("ddlApprovalStatus");
acceptStatus = DDLP.SelectedValue;
debugLabel.Text += acceptStatus + ", ";
}
}
The debugLabel.Text always ends up being "accept, accept, accept..." even when the DropDownLists have "Reject" selected.
Reproduced and fixed your problem by handling post-back events.
default.aspx.cs
using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
namespace DropdownClicks
{
public partial class WebForm1 : System.Web.UI.Page
{
static List<string> itemsToInsert = new List<string> { "first", "second", "third" };
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
//only do this binding on page load, otherwise you'll "reset" the grid every time there is a postBack.
mydg.DataSource = itemsToInsert;
mydg.DataBind();
}
}
protected void Unnamed_Click(object sender, EventArgs e)
{
DropDownList DDLP;
string acceptStatus;
string retVal = "";
for (int i = 0; i < mydg.Items.Count; i++)
{
DDLP = (DropDownList)mydg.Items[i].FindControl("ddlApprovalStatus");
acceptStatus = DDLP.SelectedValue;
retVal += acceptStatus + ", ";
}
lbl_1.Text = retVal;
}
}
}
default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="DropdownClicks.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label Text="text" runat="server" ID="lbl_1" />
<asp:DataGrid runat="server" ID="mydg" EnableViewState="true">
<Columns>
<asp:TemplateColumn HeaderText="Actions">
<HeaderStyle CssClass="ProfDataGridHeader" BorderStyle="Solid" BorderWidth="1"></HeaderStyle>
<ItemStyle Width="45%" CssClass="ProfDataGridRow" BorderStyle="Solid" BorderWidth="1"></ItemStyle>
<ItemTemplate>
<asp:DropDownList ID="ddlApprovalStatus" AppendDataBoundItems="True" runat="server" Width="150px" EnableViewState="true" ViewStateMode="Enabled">
<asp:ListItem Value="approve" Text="Approve"></asp:ListItem>
<asp:ListItem Value="reject" Text="Reject"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
<asp:Button Text="click me" runat="server" OnClick="Unnamed_Click" EnableViewState="true" />
</div>
</form>
</body>
</html>
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();
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();
// ...
}
}