I have this itemtemplate for a gridview column that is pulling data from a SQL database. My Question is how would I perform a check to see if my field ActivityFile has a value (which means a file is in the db) and then display the LinkButton at which point I generate code to download the file (already done and works).
<ItemTemplate>
<asp:LinkButton ID="DownloadFileBtn" runat="server" visible="false">Download File</asp:LinkButton>
<br />
<asp:Label ID="Label4" runat="server" Text='<%# Bind("ActivityLink") %>'></asp:Label>
</ItemTemplate>
you have to use GridView RowDataBound Event for that
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
System.Data.DataRowView dr = (System.Data.DataRowView)e.Row.DataItem;
if (Convert.ToBoolean(dr["columnName"].ToString()))
{
LinkButton LinkButton = (LinkButton)e.Row.Findcontrol("LinkButton");
LinkButton.Visible = false;
}
}
}
Related
I am trying to pass a session value from a gridview select row using GridView1_RowEditing1 event. i am able to get session value for primarykey (p.key) but the Associate_ID returns empty.
C# Code behind
protected void GridView1_RowEditing1(object sender, GridViewEditEventArgs e)
{
int primarykey = Convert.ToInt32(GridView1.DataKeys[e.NewEditIndex].Value);
string name = Convert.ToString(GridView1.Rows[e.NewEditIndex].FindControl("Associate_ID"));
Session["Number"] = primarykey;
Session["Name"] = name;
//redirect
Response.Redirect("updatee.aspx");
}
.ASPX
<asp:TemplateField HeaderText="Associate_ID" SortExpression="Associate_ID">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Associate_ID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Associate_ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
OUTPUT:
Key: 5
Name:
As you can see i am not getting Associate_ID for selected field.
Also tried using
string name = Convert.ToString(GridView1.Rows[3].Cells[3].FindControl("Associate_ID"));
but there was no result, the grid has multiple columns and rows (8*15)
tried suggestions on gridview findcontrol returning empty "" and tried stopping re-binding the GridView on the PostBack.
removed DataSourceID from gridview
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" OnRowEditing="GridView1_RowEditing1" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//DataSourceID = "SqlDataSource1"
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
}
}
None of this helped. I am still getting a blank value for Associate_ID.
i am unable to see where the issue is. Please help!
You are trying to find the Control Associate_ID with FindControl. But it does not exist. Either find TextBox1 or rename the TextBox to Associate_ID.
<EditItemTemplate>
<asp:TextBox ID="Associate_ID" runat="server" Text='<%# Bind("Associate_ID") %>'></asp:TextBox>
</EditItemTemplate>
//or
string name = Convert.ToString(GridView1.Rows[3].Cells[3].FindControl("TextBox1"));
UPDATE
I see the problem, somehow you are trying to access those control before the edit state has been activated by rebinding the GridView. The edit index has not been set. So place this before the FindControl.
GridView1.DataSource = yourSource;
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
Thank you so much VDWWD, i was finally able to get it to work.
The problem was i was not able to use get my 'TextBox' element in gridview using FindControl.
The solution was to not re-binding the GridView on the PostBack of the page and edit index on the RowEditing event.
This is what my working code looks like, is any one ever comes across a similar issue
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.DataSource = SqlDataSource1;
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
TextBox txt = GridView1.Rows[e.NewEditIndex].FindControl("TextBox1") as TextBox;
string name = txt.Text;
}
.ASPX
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("CountryName") %>'></asp:TextBox>
</EditItemTemplate>
While getting the value I'm getting Object reference not set to an instance of an object. how to get labeled label value in code behind. How to get the value in custom event
<asp:GridView runat="server" ID="gridviewQuoteDetails" EmptyDataText="No records Found..." AutoGenerateEditButton="false" OnRowEditing="gridviewQuoteDetails_RowEditing" OnRowUpdating="gridviewQuoteDetails_RowUpdating" DataKeyNames="id" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<a href='Quote.aspx?val=<%#Eval("id")%>'>
<asp:Label ID="lblid" runat="server" Text='<%#Eval ("id")%>'></asp:Label>
</a>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" Text="Edit" runat="server" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="LinkButton2" Text="Update" runat="server" OnClick="OnUpdate" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
code behind
protected void OnUpdate(object sender, EventArgs e)
{
string qouteid = ((Label)gridviewQuoteDetails.FindControl("lblid")).Text;
GridViewRow row = (sender as LinkButton).NamingContainer as GridViewRow;
string id = (row.Cells[0].Controls[0] as TextBox).Text;
string Description = (row.Cells[1].Controls[0] as TextBox).Text;
}
Gridview is a collection of rows right, but you are trying to search the control directly within the gridview thus ((LinkButton)gridviewQuoteDetails.FindControl("lbllnknm")) will be null and when you are trying to access the Text property of LinkButton you are getting NRE error.
You need to loop through the rows of your gridview control to access each linkbutton present in each row like this:-
foreach (GridViewRow row in gridviewQuoteDetails.Rows)
{
LinkButton lbllnknm= row.FindControl("lbllnknm") as LinkButton;
}
But ideally you would not be needing this. I guess you are trying to get the value in OnRowEditing event handler. If that is the case then you can fetch the value of linkbutton like this:-
protected void gridviewQuoteDetails_RowEditing(object sender, GridViewUpdateEventArgs e)
{
string qouteid = ((Label)gridviewQuoteDetails.Rows[e.NewEditIndex]
.FindControl("lbllnknm")).Text;
}
Update 2:
As per your comment you are trying to access the LinkButton text on click of LinkButton itself which means the event is raised by LinkButton itself. You can simply use the sender object like this:-
protected void OnUpdate(object sender, EventArgs e)
{
LinkButton LinkButton2 = sender as LinkButton;
GridViewRow row = LinkButton2.NamingContainer as GridViewRow; //Get the gridview row
Label lblid = row.FindControl("lblid") as Label;
string qouteid = lblid.Text;
}
I have written code like below lines of code
protected void grdView_DataBinding(object sender, EventArgs e)
{
LicenceBL lbl = new LicenceBL(0);
DataSet lds = new DataSet();
lbl.FetchForEdit(lds, LicenseType);
foreach (GridViewRow row in grdView.Rows)
{
Label lblJurisdiction = row.FindControl("lblJurisdiction") as Label;
TextBox txtDateIssued = row.FindControl("txtEffectiveDate") as TextBox;
TextBox txtDateExpiration = row.FindControl("txtExpirationDate") as TextBox;
TextBox txtLicenseNumber = row.FindControl("txtLicenseNumber") as TextBox;
for (int i = 0; i < lds.Tables[0].Rows.Count; i++)
{
txtLicenseNumber.Text = lds.Tables[0].Rows[i]["LicenceNumber"].ToString();
}
}
}
I want to bind grid view without using datasource property of gridview. The above code is not working...
Let's Suppose lds contains data like
=====================================================
LicenceNumber - LicenceIssueDate
123 - 12/10/2014
345 - 12/1/2013
=====================================================
Similarily Grid will also contain the data
=====================================================
LicenceNumber - LicenceIssueDate
123 - 12/10/2014
345 - 12/1/2013
=====================================================
Here is grid view's design
<asp:GridView ID="grdView" AutoGenerateColumns="false" OnDataBinding="grdView_DataBinding" BorderWidth="0" runat="server" CssClass="table">
<Columns>
<asp:TemplateField HeaderText="License Number">
<ItemTemplate>
<asp:TextBox ID="txtLicenseNumber" style="padding:12px 5px;" runat="server" />
<br />
<asp:RequiredFieldValidator ID="ValReqLN" Display="Dynamic" runat="server"
ErrorMessage="License Number cannot be Blank." ControlToValidate="txtEffectiveDate"></asp:RequiredFieldValidator>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Effective Date">
<ItemTemplate>
<asp:TextBox ID="txtEffectiveDate" style="padding:12px 5px;" placeholder="(mm/dd/yyyy)" CssClass="datepiker" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Please help!!!
Why would you not use datasource property ? you said: "i want to bind gridview programically because I have to give many conditions inside gridview's rows according to business logic in order to display data in the gridview.
Here is how you can do that:
Code behind:
protected void grdView_DataBinding(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView drv = e.Row.DataItem as DataRowView;
if (drv["txtLicenseNumber"].ToString().ToLower() == "abc")
{
//Apply business logic here on each row, hide/show etc
e.Row.CssClass = "highlighted";
}
}
}
Read more here on:
Dynamically change GridView Cell value using RowDataBound event in ASP.Net using C# and VB.Net
Selectively apply css to a row in a gridview
I have a LinkButton within my ItemTemplate of my ListView:
<asp:ListView ID="lvNotification" runat="server">
<ItemTemplate>
<asp:LinkButton runat="server" ID="lbReject" OnClick="Reject_Click" CommandArgument='<%# Eval("offerID") %>' Text="Reject" />
</ItemTemplate>
</asp:ListView>
Then in my code I have:
protected void Reject_Click(object sender, EventArgs e)
{
var lbreject = lvNotification.Items[0].FindControl("lbReject") as LinkButton;
string c = lbreject.CommandArgument;
}
The ListView retrieves 4 rows correctly, and I have placed the Eval("offerID") and it shows an offerID for each item in the list, however when I place it as the CommandArgument in the LinkButton and debug it, it shows the value 1 on ever item in the ListView, I am trying to place the offerID in each LinkButton CommandArgument and be able to access it, but I cannnot do so.
What am I doing wrong?
That is because you are always checking the first item (0 index). You can get the LinkButton from the sender and check its command argument.
protected void Reject_Click(object sender, EventArgs e)
{
var lbreject = (LinkButton)sender;
string c = lbreject.CommandArgument;
}
Here actually OnItemCommand event of ListView can be handy. This way you can control all events from the single point:
<asp:ListView ID="lvNotification" OnItemCommand="lvNotification_OnItemCommand" runat="server">
<ItemTemplate>
<asp:LinkButton runat="server" ID="lbReject" CommandName="Reject_Click" CommandArgument='<%# Eval("offerID") %>' Text="Reject" />
</ItemTemplate>
</asp:ListView>
protected void lvNotification_OnItemCommand(object sender, ListViewCommandEventArgs e)
{
if (String.Equals(e.CommandName, "Reject_Click"))//or any other event
{
LinkButton lbreject = (LinkButton) sender;
string c = lbreject.CommandArgument;
}
}
I am using a gridview, and here is one of my templatefields:
<asp:TemplateField HeaderText="Quantity" SortExpression="Quantity">
<HeaderTemplate>
<asp:Label ToolTip="Quantity" runat="server" Text="Qty"></asp:Label>
</HeaderTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_Quantity" runat="server" Text='<%# Bind("Quantity") %>' Width="30px"
Enabled='True'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
I am tring to reach txt_Quantity like this
protected void begv_OrderDetail_RowCreated(object sender, GridViewRowEventArgs e)
{
TextBox txt_Quantity = (TextBox)e.Row.FindControl("txt_Quantity");
txt_Quantity.Attributes.Add("onFocus", "test(this)");
}
This is the error message:
System.NullReferenceException: Object reference not set to an instance
of an object.
RowCreated is executed for every RowType(btw, the same as with RowDataBound), so for the header, data-row, footer or pager.
The first row is the header-row, but the TextBox is in rows with RowType=DataRow. Since it's in the EditItemTemplate you also have to check the EditIndex:
protected void begv_OrderDetail_RowCreated(object sender, GridViewRowEventArgs e)
{
if (row.RowType == DataControlRowType.DataRow
&& e.Row.RowIndex == begv_OrderDetail.EditIndex)
{
TextBox txt_Quantity = (TextBox)e.Row.FindControl("txt_Quantity");
txt_Quantity.Attributes.Add("onFocus", "test(this)");
}
}
Note that if you enumerate the Rows property of the GridView you only get the rows with RowType=DataRow, so the header, footer and pager are omitted. So here no additional check is needed:
foreach(GridViewRow row in begv_OrderDetail.Rows)
{
// only DataRows
}