I tried to get the control of edit template which is checkbox in row command event but I am unable to get it, but I am getting label control which is in row index.
I tried the above below code to get the control:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
Label icllbl = (Label)GridView1.Rows[gvr.RowIndex].FindControl("icllbl");
CheckBox iclcb = (CheckBox)GridView1.Rows[gvr.RowIndex].FindControl("iclcb");
if (e.CommandName.Equals("Edit"))
{
if (icllbl.Text == "Y")
{
iclcb.Checked = true;
}
}
}
And I tried RowDataBound event also luckily I am getting checkbox control here but this time I am unable to get the Label control in below code:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label icllbl = (Label)e.Row.FindControl("icllbl");
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
CheckBox iclcb = (CheckBox)e.Row.FindControl("iclcb");
if (icllbl.Text == "Y")
{
iclcb.Checked = true;
}
}
}
}
Please correct me if I am wrong anywhere.
Thanks in advance!
In your RowCommand event use control class to cast into GridViewRow:
GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);
int rowIndex = row.RowIndex;
And in RowDataBound event place Label control inside Edit (check for EditTemplate) check:
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
Label icllbl = (Label)e.Row.FindControl("icllbl");
CheckBox iclcb = (CheckBox)e.Row.FindControl("iclcb");
//... other code of lines will be here
}
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('_');
}
}
I want to set the gridview row color if a specific column has a value. But I got an error about nullreference in my DIVSTATUS.
My ASPX
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<div style="width:70px;" id="divStatus" runat="server"><%# Eval("DscStatus")%></div>
</ItemTemplate>
</asp:TemplateField>
My Code-Behind
if (GridView1.Rows.Count > 0)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
HtmlContainerControl divstatus = (HtmlContainerControl)GridView1.Rows[i].FindControl("divstatus");
if (divstatus != null)
{
if (divstatus.InnerText == "Andamento Project")
{
GridView1.Rows[i].BackColor = System.Drawing.Color.Navy;
GridView1.Rows[i].ForeColor = System.Drawing.Color.White;
}
}
}
}
My Rendered HTML
<td>
<div style="width:70px;">Andamento Project</div>
</td>
Make use of RowDataBound property and do code as below ...you dont need to get the div status you just get your datatype and in that datatype you get the value of your property by using than value of property you can decide the color of you row
protected void grdCAPRate_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
yourtype obj= (yourtype)e.Row.DataItem;
if (obj.DscStatus == "Andamento Project")
e.Row.BackColor = System.Drawing.Color.Navy;
else
e.Row.ForeColor=System.Drawing.Color.White;
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HtmlContainerControl divstatus = (HtmlContainerControl) e.Row.FindControl("divstatus");
if (divstatus != null)
{
if (divstatus.InnerText == "Andamento Project")
{
e.Row.BackColor = Color.Navy;
e.Row.ForeColor = Color.White;
}
}
}
}
I have one table like employee and one of its row is 'status'.
If status value is 'approve' then I want to show that row in a green color
otherwise I want to show it in a red color.
I have tried following but it is not working
if (e.Row.RowType == DataControlRowType.Header)
{
string status = DataBinder.Eval(e.Row.DataItem, "IsApprove").ToString();
if (status == "pending")
{
e.Row.ForeColor = System.Drawing.Color.Red; // Change the row's Text color
}
}
ALSO THIS ONE
private void gvleavedetail_cellformatting(object sender, datagridviewcellformattingeventargs e)
{
// if the column is the artist column, check the
// value.
if (this.gvleavedetail.columns[e.columnindex].name == "artist")
{
if (e.value != null)
{
// check for the string "pink" in the cell.
string stringvalue = (string)e.value;
stringvalue = stringvalue.tolower();
if (stringvalue == "high")
{
e.cellstyle.backcolor = color.pink;
}
}
}
But in this case i'm getting error for datagridviewcellformattingeventargs
I'm using VS2010
hi all i got the solution plz c this one ;)
just write the following condition code on RowDataBound EVENT OF GRIDVIEW
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string status = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "IsApprove"));
if (status == "pending")
{
e.Row.Cells[7].ForeColor = System.Drawing.Color.Yellow;
}
else if(status== "accept")
{
e.Row.Cells[7].ForeColor = System.Drawing.Color.Green;
}
else if (status == "reject")
{
e.Row.Cells[7].ForeColor = System.Drawing.Color.Red;
}
}
}
I have a gridview and I need to make an event fire when a row is clicked.
Is there an existing GridView event I need to bind to to make this happen?
Here's something I prepared earlier:
public class RowClickableGridView : GridView
{
public Style HoverRowStyle
{
get { return ViewState["HoverRowStyle"] as Style; }
set { ViewState["HoverRowStyle"] = value; }
}
public bool EnableRowClickSelection
{
get { return ViewState["EnableRowClickSelection"] as bool? ?? true; }
set { ViewState["EnableRowClickSelection"] = value; }
}
public string RowClickCommand
{
get { return ViewState["RowClickCommand"] as string ?? "Select"; }
set { ViewState["RowClickCommand"] = value; }
}
public string RowToolTip
{
get
{
if (!RowToolTipSet) return string.Format("Click to {0} row", RowClickCommand.ToLowerInvariant());
return ViewState["RowToolTip"] as string;
}
set
{
ViewState["RowToolTip"] = value;
RowToolTipSet = true;
}
}
private bool RowToolTipSet
{
get { return ViewState["RowToolTipSet"] as bool? ?? false; }
set { ViewState["RowToolTipSet"] = value; }
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
foreach (GridViewRow row in Rows)
{
if (row.RowType != DataControlRowType.DataRow) continue;
if (EnableRowClickSelection && row.RowIndex != SelectedIndex && row.RowIndex != EditIndex)
{
if (string.IsNullOrEmpty(row.ToolTip)) row.ToolTip = RowToolTip;
row.Style[HtmlTextWriterStyle.Cursor] = "pointer";
PostBackOptions postBackOptions = new PostBackOptions(this,
string.Format("{0}${1}",
RowClickCommand,
row.RowIndex));
postBackOptions.PerformValidation = true;
row.Attributes["onclick"] = Page.ClientScript.GetPostBackEventReference(postBackOptions);
foreach (TableCell cell in row.Cells)
{
foreach (Control control in cell.Controls)
{
const string clientClick = "event.cancelBubble = true;{0}";
WebControl webControl = control as WebControl;
if (webControl == null) continue;
webControl.Style[HtmlTextWriterStyle.Cursor] = "Auto";
Button button = webControl as Button;
if (button != null)
{
button.OnClientClick = string.Format(clientClick, button.OnClientClick);
continue;
}
ImageButton imageButton = webControl as ImageButton;
if (imageButton != null)
{
imageButton.OnClientClick = string.Format(clientClick, imageButton.OnClientClick);
continue;
}
LinkButton linkButton = webControl as LinkButton;
if (linkButton != null)
{
linkButton.OnClientClick = string.Format(clientClick, linkButton.OnClientClick);
continue;
}
webControl.Attributes["onclick"] = string.Format(clientClick, string.Empty);
}
}
}
if (HoverRowStyle == null) continue;
if (row.RowIndex != SelectedIndex && row.RowIndex != EditIndex)
{
row.Attributes["onmouseover"] = string.Format("this.className='{0}';", HoverRowStyle.CssClass);
row.Attributes["onmouseout"] = string.Format("this.className='{0}';",
row.RowIndex%2 == 0
? RowStyle.CssClass
: AlternatingRowStyle.CssClass);
}
else
{
row.Attributes.Remove("onmouseover");
row.Attributes.Remove("onmouseout");
}
}
}
protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
foreach (GridViewRow row in Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
Page.ClientScript.RegisterForEventValidation(row.ClientID);
}
}
}
}
You then hook into the standard row command events...
Some javascript programming will be required in order to make this happen.
Basically you are going to have to handle the click event for the row(is some browsers the row does not have a click event so you might have to handle the click event of the tds... time to invest in an ajax framework!)
You will then from javascript have to fire a postback with the row index as a parameter. See encosia(a great site for ASP.Net - ajax implementations) on how to do that. Here is a link to an article along those lines
This can be done easily by adding a dummy LinkButton with no Text to the GridView and some code in the RowDataBound.
The LinkButton is needed on the page to avoid the Invalid postback or callback argument error. Setting the visibility to false will also cause this error.
The LinkButton also has a CommandArgument with the current row number and a OnCommand event to handle the actual clicking.
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandArgument='<%# Container.DataItemIndex %>' OnCommand="LinkButton1_Command"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
The OnRowDataBound method
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//check if the row is a datarow
if (e.Row.RowType == DataControlRowType.DataRow)
{
//find the linkbutton with findcontrol and cast it back to one
LinkButton lb = e.Row.FindControl("LinkButton1") as LinkButton;
//create the correct postback event with the UniqueID property of the linkbutton
string href = "javascript:__doPostBack('" + lb.UniqueID + "','')";
//add the onclick event with the correct href to the row
e.Row.Attributes.Add("onclick", href);
//to make it visible to the user that the row can be clicked
e.Row.Attributes.Add("style", "cursor:pointer;");
}
}
And the Command Method where you can get the CommandArgument from the LinkButton and do all sorts of neat things with it.
protected void LinkButton1_Command(object sender, CommandEventArgs e)
{
//the row index of the clicked row from the grid if needed
int rowIndex = Convert.ToInt32(e.CommandArgument);
//do stuff
}
There is no existing event to handle an entire row click. Your best bet is to have some javascript (maybe via ASP.NET Ajax) detect the click and fire the event yourself. Alternatively you would have to create a button or checkbox that the user selects.
You need to handle the "SelectedIndexChanged" event, you can then query the grid for the .SelectedRow. Alternativley use the "SelectedIndexChanging" event which sets "e.NewSelectedIndex"
Check out this article by Teemu, in where he explains about clicking a row in Gridview and throw the RowClicked event.
Here is a excerpt of the code:
Protected Overrides Sub RaisePostBackEvent(ByVal eventArgument As String)
If eventArgument.StartsWith("rc") Then
Dim index As Integer = Int32.Parse(eventArgument.Substring(2))
Dim args As New GridViewRowClickedEventArgs(Me.Rows(index))
OnRowClicked(args)
Else
MyBase.RaisePostBackEvent(eventArgument)
End If
End Sub
Public Class GridViewRowClickedEventArgs
Inherits EventArgs
Private _row As GridViewRow
Public Sub New(ByVal row As GridViewRow)
_row = row
End Sub
Public ReadOnly Property Row() As GridViewRow
Get
Return _row
End Get
End Property
End Class
Btw, it's in VB not C# though.