Conditional formatting on an entire column in Gridview - c#

I need to format 2 entire columns in my gridview based on if the cell contains the string "yes" or "no". I've looked everywhere trying to find something accomplishing what I'm trying to do and cant find anything based on a string, only int values.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView gv = (GridView)e.Row.FindControl("GridView2");
var ds = new SqlDataSource();
ds.ConnectionString = ConfigurationManager.ConnectionStrings["HUTDMSConnectionString"].ConnectionString;
ds.SelectCommand = "SELECT * FROM textBooks WHERE CourseID = '" + GridView1.DataKeys[e.Row.RowIndex].Value + "' ORDER BY BookTitle";
gv.DataSource = ds;
gv.DataBind();
}
}
I know that the conditional formatting goes within the gridview_rowdatabound
event.
What I have so far:
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.DataRow && ((e.Row.RowState & DataControlRowState.Edit) == 0))
{
var valueFetched = ((TableCell)(e.Row.Cells[3].FindControl("no"))).Text;
if (valueFetched == "no")
{
foreach (var cell in e.Row.Cells)
((TableCell)cell).BackColor = Color.Red;
}
}
}

Look at this example to get some direction. This code goes under RowDataBound
if (e.Row.RowType == DataControlRowType.DataRow && ((e.Row.RowState & DataControlRowState.Edit) == 0))
{
var valueFetched = ((Label)(e.Row.Cells[1].FindControl("yourControlId"))).Text;
if (valueFetched == "1")
{
foreach (var cell in e.Row.Cells)
((TableCell)cell).BackColor = System.Drawing.Color.LightBlue;
}
}

Related

Getting the value of Full-Row Clickable Gridview and Display in Textbox

I have a gridview that loads data from a stored procedure.
OBJECTIVE:
to make the full gridview row clickable by hiding the select column in the gridview - I was able to do this by doing the code below in the RowDataBound event.
Next is when I click a full row in the gridview, I should be able to get the data / values from the row selected and display this in the textboxes in the modal pop up to appear. This is for UPDATING / EDITING FUNCTIONS.
Here's what I have got
protected void grdTenant_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[0].Style["display"] = "none";
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] =
"javascript:setMouseOverColor(this);";
e.Row.Attributes["onmouseout"] =
"javascript:setMouseOutColor(this);";
e.Row.Attributes["onclick"] =
Page.ClientScript.GetPostBackClientHyperlink
(this.grdTenant, "Select$" + e.Row.RowIndex);
e.Row.Attributes.Add("onclick", String.Format("javascript:$find('{0}').show();",ModalEditTenant.ClientID ));
//this line does not work in retrieving row data
IDataRecord dataRow = (IDataRecord)e.Row.DataItem;
txtRPCode.Text = Convert.ToString(dataRow["Retail Partner"]);
}
}
As an alternative, I do this to achieve the second goal but fails to do the first
protected void grdTenant_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = grdTenant.SelectedRow;
txtRPCode.Text = row.Cells[1].Text;
ModalEditTenant.Show();
}
But, this method works only when the select button column is visible and when it is clicked, it fails to do so when the full row is selected.
How can I make the full row select and retrieves the data to textbox successfully (with the select column hidden)
This is how gridview bind the data from the stored procedure datasource.
System.Threading.Thread.Sleep(500);
//DropDownList ddl = (DropDownList)sender;
SqlCommand cmd = new SqlCommand("spTenantList", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Location", ddlSelectLoc.SelectedValue );
try
{
con.Open();
grdTenant.EmptyDataText = "No Records Found";
grdTenant.DataSource = cmd.ExecuteReader();
grdTenant.DataBind();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
Use FindControl()method.
Instead of txtRetailPartner place your TextBox ID.
txtRPCode.Text = ((TextBox)e.Row.FindControl("txtRetailPartner")).Text;
Use my logic below in RowDataBound event to get DataItem:
protected void grdTenant_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[0].Style["display"] = "none";
if (e.Row.RowType == DataControlRowType.DataRow)
{
IDataRecord dataRow = (IDataRecord)e.Row.DataItem;
txtRPCode.Text = Convert.ToString(dataRow["Retail Partner Code"]);
}
}
I have found the answer based on what is to achieved. Using my current codes posted as question , Just remove the one line code there and it will work
protected void grdTenant_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[0].Style["display"] = "none";
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] =
"javascript:setMouseOverColor(this);";
e.Row.Attributes["onmouseout"] =
"javascript:setMouseOutColor(this);";
e.Row.Attributes["onclick"] =
Page.ClientScript.GetPostBackClientHyperlink
(this.grdTenant, "Select$" + e.Row.RowIndex);
}
}
This line is removed:
//This is no longer needed as it will make the onselectedindexchanged event ineffective as this will be run first.
e.Row.Attributes.Add("onclick", String.Format("javascript:$find('{0}').show();",ModalEditTenant.ClientID ));
protected void grdTenant_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = grdTenant.SelectedRow;
txtRPCode.Text = row.Cells[1].Text;
ModalEditTenant.Show();
}
And everything will work as expected.

asp.net repeater for each row

I have a repeater that retrieve data from my db.
some of the results are getting a null value in a specific column due to
a join query and its fine.
I would like to go over each row and if the result is null for the specific
row i want to change the css for this row.
Now for the code:
<asp:Repeater ID="repRequests" OnItemDataBound="repRequests_ItemDataBound" runat="server">
<ItemTemplate>
<asp:Label ID="lbltest" runat="server" Text='<%#Eval("val_name") %>'></asp:Label>
</ItemTemplate>
</asp:Repeater>
C#:
if (!IsPostBack)
{
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("check_accepted", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#val_name", Session["valName"].ToString());
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
repRequests.DataSource = dr;
repRequests.DataBind();
}
}
How to write this ?
protected void repRequests_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
**//what i want to get:**
if (dr["accepted_id"] == Null) // a column from the db table
{
repRequests.attribute["class"] = "Some Class"
}
}
}
Thanks for the helpers !
You can try the following. If the data source is a DataReader object, you must cast e.Item.DataItem as type DBDataRecord (from System.Data.Common)
protected void repRequests_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
System.Data.Common.DbDataRecord dataRow = e.Item.DataItem as System.Data.Common.DbDataRecord;
if (dataRow["accepted_id"] == DBNull.Value || dataRow["accepted_id"] == null) // a column from the db table
{
// I am not sure how to you get repRequests. but you can find the control using e.Row.Item.FindControl() function
repRequests.attribute["class"] = "Some Class";
}
}
}
EDIT
Further to your questions, if you want to change the css of a perticular row, if some value is null, you cannot set css to repeater or repeater item directly. What you need to do is add a top level panel to the ItemTemplate like this
<ItemTemplate>
<asp:Panel runat="server" ID="panelRow">
<asp:Label ID="lbltest" runat="server" Text='<%#Eval("val_name") %>'></asp:Label>
</asp:Panel>
</ItemTemplate>
Then you can change the css of the panel like below
protected void repRequests_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
System.Data.Common.DbDataRecord dataRow = e.Item.DataItem as System.Data.Common.DbDataRecord;
if (dataRow["accepted_id"] == DBNull.Value || dataRow["accepted_id"] == null) // a column from the db table
{
Panel panelRow = e.Item.FindControl("panelRow") as Panel;
panelRow.CssClass = "yourcssclass";
}
}
}
If not, you can use IsNull in your query.
SqlCommand cmd = new SqlCommand("select IsNull(something,zero) from sometable",connectionstring)
SqlDatareader dr = cmd.ExecuteReader();
while(dr.Read())
{
if(dr.GetString(0)=="zero")
{
repRequests.attribute["class"] = "Some Class";
}
}
Here is link example of DbDataRecord when you bind repeater control with sqldatareader.
Also note that repRequests.attribute["class"] = "Some Class" this means you are applying CSS Class to the repeater control. You need to change the CssClass label which is used as item of repeater control.
protected void repRequests_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
DbDataRecord dbr = (DbDataRecord)e.Item.DataItem;
if( Convert.ToString(DataBinder.Eval(dbr, "accepted_id")) == null )
((Label)e.Item.FindControl("lbltest")).CssClass = "Some Class";
}
}

Asp Net Gridview sort disapears when row edit

when I click on the line update the gridview sort of disappears and returns to its initial state. what can be?
Below transcribe my code:
private string GetSortDirection(string column)
{
// By default, set the sort direction to ascending.
string sortDirection = "ASC";
// Retrieve the last column that was sorted.
string sortExpression = ViewState["SortExpression"] as string;
if (sortExpression != null)
{
// Check if the same column is being sorted.
// Otherwise, the default value can be returned.
if (sortExpression == column)
{
string lastDirection = ViewState["SortDirection"] as string;
if ((lastDirection != null) && (lastDirection == "ASC"))
{
sortDirection = "DESC";
}
}
}
// Save new values in ViewState.
ViewState["SortDirection"] = sortDirection;
ViewState["SortExpression"] = column;
return sortDirection;
}
protected void GridViewLayoutProduto_Sorting(object sender, GridViewSortEventArgs e)
{
//Retrieve the table from the session object.
DataTable dt = Session["TaskTable"] as DataTable;
if (dt != null)
{
//Sort the data.
dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
Session["TaskTable"] = dt;
GridViewLayoutProduto.DataSource = Session["TaskTable"];
GridViewLayoutProduto.DataBind();
}
}
protected void GridViewLayoutProduto_RowEditing(object sender, GridViewEditEventArgs e)
{
GridViewLayoutProduto.EditIndex = e.NewEditIndex;
//CheckBox alt = GridViewLayoutProduto.Rows[e.NewEditIndex].FindControl("CheckBox1") as CheckBox;
//alt.Enabled = false;
BindData();
}
protected void GridViewLayoutProduto_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridViewLayoutProduto.PageIndex = e.NewPageIndex;
GridViewLayoutProduto.DataBind();
}
protected void GridViewLayoutProduto_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridViewLayoutProduto.EditIndex = -1;
BindData();
}
private void BindData()
{
GridViewLayoutProduto.DataSource = Session["TaskTable"];
GridViewLayoutProduto.DataBind();
}
in the session data the datatable to stored will not be organized, how can I store in a session with the datatble sort performed.
Try Putting this line after Sort of GridView
Session["TaskTable"] = ((DataView)gvProgramlar.DataSource).ToTable();
Hope this helps you!

No mapping exists from object type System.Web.UI.WebControls.GridViewRow to a known managed provider native type

I want to make a gridview that when I select a row, its values will be populated to another gridview and text boxes, but I am encountering the error above. When I click the row in the GridView2, nothing is happening and an error in the sqladapter occurs. Please help me to fix this code..
Here is my code:
c#
protected void GridView2_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(conn);
SqlCommand com = new SqlCommand("SELECT MRPNo, MRPType, MRPDate FROM MRP WHERE MRPNo = #mrpno",con);
com.Parameters.Add("#mrpno", GridView2.SelectedRow);
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(com);
sda.Fill(dt);
DataRow row = dt.Rows[0];
txtMRPNo.Text = row["MRPNo"].ToString();
txtMRPDate.Text = row["MRPType"].ToString();
txtMRPDate.Text = row["MRPDate"].ToString();
GridView3.DataBind();
GridView1.DataBind();
}
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
LinkButton selectButton = new LinkButton()
{
CommandName = "Select",
Text = e.Row.Cells[0].Text,
};
e.Row.Cells[0].Controls.Add(selectButton);
}
protected void GridView2_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] = "this.style.cursor='pointer';this.style.textDecoration='underline';";
e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
e.Row.ToolTip = "Click to select row";
e.Row.Attributes["onclick"] = this.Page.ClientScript.GetPostBackClientHyperlink(this.GridView2, "Select$" + e.Row.RowIndex);
}
}
}
You can not use GridView2.SelectedRow as an input to Parameters.Add(). Please refer to MSDN (http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.selectedrow(v=vs.110).aspx) and you will see why.

How to sorting the gridview when i click the header text on gridview in asp.net

I have developed an asp.net application that has a Gridview control. I want it to sort when I click on the Gridview header text in asp.net. Entity framework is used to bind the gridview.
protected void grdmortgagesaver_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, DESCENDING);
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, ASCENDING);
}
}
private void SortGridView(string sortExpression, string direction)
{
// You can cache the DataTable for improving performance
var databind = from i in mortgageentites.Clients orderby i.LastName select i;
if (databind.Count() > 0)
{
grdmortgagesaver.DataSource = databind.ToList();
grdmortgagesaver.DataBind();
DataTable dt = clients;
if (dt != null)
{
// DataTable dt = ds.Tables[0];
DataView dv = new DataView(dt);
dv.Sort = sortExpression + direction;
grdmortgagesaver.DataSource = dv;
grdmortgagesaver.DataBind();
}
}
}
If you are using a standard ASP.NET System.Web.UI.WebControls.GridView, you can simply "Enable Sorting", in the properties pane by setting "AllowSorting" to true or via the "pop-out" on the top right of the control by checking "Enable Sorting"
add AllowSorting="true" in your gridview control and
protected void grd_Sorting(object sender, GridViewSortEventArgs e)
{
if (e.SortExpression == hdfSortExp.Value)
{
if (hdfUpDown.Value == "1")
hdfUpDown.Value = "0";
else
hdfUpDown.Value = "1";
}
else //New Column clicked so the default sort direction will be incorporated
hdfUpDown.Value = "0";
hdfSortExp.Value = e.SortExpression; //Update the sort column
BindGrid(hdfSortExp.Value, this.CBool(hdfUpDown.Value));
}
in your c# code
public void BindGrid(string sortBy, bool inAsc)
{
grd.DataSource = WManager.GetAdminTags(txtSearch.Text.Trim(), sortBy, inAsc);
grd.DataBind();
}
First in your Page in the GridView Declaration Tag add the property AllowSorting="true" and in the Gridview_SortCommand try the Following code as guidence
try {
if (SortType == false) {
SortView.Sort = e.SortExpression + " ASC";
//dviewGeneral.Sort = e.SortExpression & " ASC"
Session.Item("SortOrder") = SortView.Sort.ToString;
SortType = true;
} else {
SortView.Sort = e.SortExpression + " DESC";
Session.Item("SortOrder") = SortView.Sort.ToString;
//dviewGeneral.Sort = e.SortExpression & " DESC"
SortType = false;
}
CMSgrid.SelectedIndex = -1;
CMSgrid.CurrentPageIndex = 0;
SortBind();
} catch (Exception ex) {
UserMsgBox(ex.ToString());
}

Categories

Resources