I am using the below code to disable row in gridview where the column name is test. Everything works fine except for the first row. The color does not get applied to the first row. Where am I going wrong?I also want to hide a column based on column name.
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (Hidden4.Value == "Data Present")
{
foreach (GridViewRow item in GdvTestData.Rows)
{
int a = GetColumnIndexByName(item, "test");
int b = GetColumnIndexByName(item, "id");
if (e.Row.RowType == DataControlRowType.DataRow)
{
string test = e.Row.Cells[a].Text;
foreach (TableCell cell in e.Row.Cells)
{
if (test == "Y")
{
cell.BackColor = Color.Gray;
e.Row.Attributes.Add("onmouseover", "alert('This data is for testing');");
}
}
e.Row.Cells[b].Visible = false;
}
}
}
}
Maybe you are confusing data/business logic and UI.
RowDataBound event works per row so you don't need to loop gridview rows.
You are working on cell content but you have data bound to those. So:
ASPX
<asp:GridView runat="server" ID="gv" ...
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" Text='<%# Eval("Test") %>' />
</ItemTemplate>
</asp:TemplateField>
...
Code Behind
private void GrdBind()
{
// populate datatable
gv.DataSource = myDataTable;
gv.Databind();
}
And the databound event:
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (Hidden4.Value == "Data Present")
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRow row = ((DataRowView)e.Row.DataItem).Row;
string test = row.Field<String>("Test");
if (test== "Y")
{
e.Row.Cells[0].BackColor = Color.Gray; // set your index
e.Row.Attributes.Add("onmouseover", "alert('This data is for testing');");
}
}
}
}
You can do this. Although I don't understand what you mean by disabling a row.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//check if the row is a datarow
if (e.Row.RowType == DataControlRowType.DataRow)
{
//cast the dataitem back to a datarowview
DataRowView row = e.Row.DataItem as DataRowView;
//find the column value in the row, not the cell text
string test = row["columnName"].ToString();
//check the value and if so apply backcolor
if (test == "Y")
{
e.Row.BackColor = Color.Red;
//or hide the row (no need to do this in Databind or OnPreRender)
e.Row.Visible = false;
}
}
}
Related
I have a grid view and need to bind IsActive field.But from the database it comes as 1 or 0.
Error shows System.InvalidCastException: 'Specified cast is not valid.'
Grid
<asp:BoundField DataField="IsActive" HeaderText="Status">
<ItemStyle Width="200px" />
</asp:BoundField>
Code
protected void grid1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (((int)DataBinder.Eval(e.Row.DataItem, "IsActive") == 1))
{
e.Row.Cells[12].Text = "Active";
}
else
{
e.Row.Cells[12].Text = "Inactive";
}
}
}
Try grabbing the underlying data item first and then checking for it.
protected void grid1_RowDataBound(object sender, GridViewRowEventArgs e)
{
DataRowView rowView = null;
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Retrieve the underlying data item
rowView = (DataRowView)e.Row.DataItem;
// Make sure we can parse and compare what we get.
if (int.TryParse(rowView["IsActive"].ToString(), out int isActive) && isActive == 1)
{
e.Row.Cells[12].Text = "Active";
}
else
{
e.Row.Cells[12].Text = "Inactive";
}
}
}
I have a GridView that displays some information about a job and one of the options in the GridView is to select a reason. If a reason isn't selected then I don't want to display that row in the GridView. How do I check if there is a value in the Reason column, and if its empty how do I hide that row?
private GridView BuildDebriefGridView()
{
GridView gv = new GridView();
gv.AutoGenerateColumns = false;
//gv.RowDataBound +=
gv.Columns.Add(new BoundField { HeaderText = "Job No", DataField = "JobNo" });
gv.Columns.Add(new BoundField { HeaderText = "Qty Rcvd", DataField = "QtyRcvd" });
gv.Columns.Add(new BoundField { HeaderText = "Reason", DataField = "Reason" });
gv.Columns.Add(new BoundField { HeaderText = "Comment", DataField = "Comment" });
gv.Attributes.Add("style", "width:100%");
return gv;
}
void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
JobPieceSerialNo item = e.Row.DataItem as JobPieceSerialNo;
if (item != null)
{
if (string.IsNullOrEmpty(item.Reason))
{
e.Row.Visible = false;
}
}
}
}
Try following;
private void gvTransportListResults_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.Cells["Reason"].Text == "")
e.Row.Visible = false;
}
Or if it is a checkbox
private void gvTransportListResults_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(((CheckBox)e.Row.FindControl("YourCheckboxID")).Checked == false)
e.Row.Visible = false;
}
Using GridView_RowDataBound event you can achieve this.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[ReasonCellNumber].Text == "Reason")
{
e.Row.Visible = false;
}
}
}
Hi all I would like to change cell index based on certain value like shown below ,I have seen many articles in here, but in ASP.NET this is a windows app how can I archive this thanks with a windows desktop app.Please Note the column that I want indexes changed is created dynamically.Thanks
Dynamic column code creation
private void button3_Click(object sender, EventArgs e)
{
DataTable table = new DataTable();
adap.Fill(table);
dataGridView1.DataSource = table;
table.Columns.Add("RESULTS").Expression = "Iif(((ActualWeight >= (.96 * TargetWeight)) And (ActualWeight <= (1.04 * TargetWeight))),'GOOD''BAD'))
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[7].Value.ToString() == "BAD")
row.Cells[7].Style.ForeColor = Color.Red;
//row.Cells["RESULTS"].Style.ForeColor = Color.Red;
}
}
As you are adding a new column to the datatable table, you need to bind the table to the datagridview (refer this : how to bind datatable to datagridview in c#) and then try to change the color.
Try this
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.ForeColor = Color.Red; //change the color to what you need
}
UPDATE : To iterate through the DataGridView and check for cell contents in a specific column, you need something like
foreach(DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[7].Value.ToString() == "BAD")
row.Cells[7].Style.ForeColor = Color.Red;
//row.Cells["RESULTS"].Style.ForeColor = Color.Red;
}
You need to place this piece of code inside an event that is triggered or function that is called after the DataGridView is populated with data.
Here is some sample code demonstrating the desired result
ASPX:
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="true">
</asp:GridView>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ArrayList al = new ArrayList();
al.Add("open"); al.Add("close"); al.Add("other"); al.Add("open"); al.Add("other"); al.Add("close"); al.Add("open");
this.GridView1.DataSource = al;
this.GridView1.DataBind();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[0].Text == "open")
{
e.Row.Cells[0].ForeColor = System.Drawing.Color.Red;
}
else if (e.Row.Cells[0].Text == "close")
{
e.Row.Cells[0].ForeColor = System.Drawing.Color.Black;
}
else
{
e.Row.Cells[0].ForeColor = System.Drawing.Color.Green;
}
}
}
I want to take LangId value in RowDataBound function. How to do this?
<asp:BoundField DataField="LangId" HeaderText="LangId" Visible="false" />
protected void grdList_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// need LangId
ImageButton imgBtn = (ImageButton)e.Row.FindControl("imgBtnDelete");
imgBtn.Visible = false;
}
}
There are a couple of ways to do it. Maybe more.
<asp:BoundField DataField="LangId" HeaderText="LangId" Visible="false" />
protected void grdList_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string langId = e.Row.Cells[columnIndex].Text; // one of the ways
string langId2 = DataBinder.Eval(e.Row.DataItem, "LangId").ToString(); // one of the other ways
}
}
You can get it by this:
string str = e.Row.Cells[CloumnIndexOfYourBoundField].Text;
ColumnIndexOfYourBoundField means if your column is first column than its index is 0 and if its second than its 1 and so on.
The data object is available as e.Row.DataItem at that time. You just need to cast it as the appropriate type.
var myItem = (MyType)e.Row.DataItem;
// myItem.LangId now available
.ASPX file:
<ItemTemplate>
<asp:ImageButton ID="imgEdit" runat="server" AlternateText="Edit"
CommandArgument='<%# Eval("LangId") %>' CommandName="DeleteLedger" ToolTip="Delete"
ImageUrl="~/App_Themes/DefaultClient/images/Delete.png" />
</ItemTemplate>
.CS file:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
DataRowView dataRow = ( DataRowView ) e.Item.DataItem;
string strLangId = dataRow["LangId"].ToString();
DataTable dtData1 =
objAccountTypeBAL.ChkLedgerRelation(Convert.ToInt64(strLangId ), objSession.BranchId);
if (dtData1.Rows.Count > 0)
{
ImageButton img = (ImageButton)item["Delete"].Controls[0];
img.Visible = false;
}
}
Using dynamic type you can access the fields in your record:
if (e.Row.RowType == DataControlRowType.DataRow)
{
dynamic data = e.Row.DataItem;
int LangId = data.LangId;
// do your code here
}
protected void GrdEmplistFromAtt_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].Attributes.Add("onmouseover", "MouseEvents(this, event)");
e.Row.Cells[0].Attributes.Add("onmouseout", "MouseEvents(this, event)");
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lbl_GrdCode = (Label)e.Row.FindControl("lblGrdCode");
}
}
I would like to change the background color of all the rows with value for "active" column unchecked in a GridView. I tried the following way but it doesn't work:
protected void GdvDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
CheckBox chkItem = null;
foreach (GridViewRow grRow in GdvDetails.Rows)
{
if (grRow.RowType == DataControlRowType.DataRow)
{
chkItem = (CheckBox)grRow.Cells[6].FindControl("active");
if (chkItem.Checked )
{
grRow.BackColor = Color.Red;
}
}
}
}
The error message is "Object reference not set to an instance of an object."
Your code doesn't work because you need to do it on RowDataBund
protected void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
//Paste your code here.
}
}
And add a handler for RowDataBound as so:
<asp:gridview id="CustomersGridView"
allowpaging="true"
onrowdatabound="CustomersGridView_RowDataBound"
runat="server">
</asp:gridview>
You need to handle RowDataBound event instead of DataBound event, so put you in RowDataBound event as below:
In aspx page, after added the event the code will look like:
<asp:gridview id="GdvDetails"
onrowdatabound="GdvDetails_RowDataBound"
runat="server">
</asp:gridview>
In code behind(.cs):
protected void GdvDetails_RowDataBoundd(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox chkItem = (CheckBox)e.Row.FindControl("active");
if (chkItem.Checked)
{
GdvDetails.SelectedRow.BackColor = Color.LightGray;
}
}
}
So this WORKS :)
protected void GdvDetails_DataBound(object sender, EventArgs e)
{
CheckBox chkItem = null;
foreach (GridViewRow grRow in GdvDetails.Rows)
{
if (grRow.RowType == DataControlRowType.DataRow)
{
chkItem = (CheckBox)grRow.Cells[6].FindControl("CkbActive");
bool bl = chkItem.Checked;
if (bl == false)
{
grRow.BackColor = Color.LightGray;
}
}
}
}
And the aspx file has
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID= "CkbActive" Checked ='<%# Bind ("active") %>' Enabled="false" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
in the GridView GdvDetails.
i didn't use the code under onrowdatabound because its an event for each row and i thought it will iterate unnecessarily. And this works... just in case anyone else is fumbling like me?!! thx for all the help