Change row color of gridview by database Values - asp.net

I am making a application in asp.net which shows the values in gridview from the database.In database i am having a colmn named as StatusId which has a value of 1 or 2 or 3.
I tried to show the grid view rows in different color by their statusId values. But it never works. How can i do it in asp.net.
Here is my code
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
Connection.Open();
SqlCommand Command1 = Connection.CreateCommand();
Command1.CommandText = "Select statusColor from status where statusId=(Select statusId from fileInfo where userId=(Select userId from userInfo where email='" + Session["email"].ToString() + "'))";
for (int i = 0; i < GridView1.Rows.Count; i++)
{
using (SqlDataReader reader = Command1.ExecuteReader())
{
while (reader.Read())
{
statusId = reader["statusColor"].ToString();
}
GridView1.RowStyle.BackColor = Color.FromName(statusId);
}
}
foreach (GridViewRow row in GridView1.Rows)
{
row.BackColor = Color.Green;
}
SqlCommand com = new SqlCommand("gridcolor", Connection);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#statusId", statusId);
com.Parameters.Add("#statusColor", SqlDbType.NVarChar, 30);
com.Parameters["#statusColor"].Direction = ParameterDirection.Output;
com.ExecuteNonQuery();
string msg = (string)com.Parameters["#statusColor"].Value;
Connection.Close();
}
What is the mistake i am doing here?
EDIT
I have the color codes which are stored in the database named as statusColor. I have to apply those color to these status.

You have statusId having values 1,2,3 and you are passing to Color.FromName which and 1,2,3 are not names of color you can use switch to assign different colors based on statusId .
Color rowColor = Color.Red;
switch(statusId)
{
case 1:
rowColor = Color.Green;
break;
case 2:
rowColor = Color.White;
break;
case 3:
rowColor = Color.Blue;
break;
}
GridView1.RowStyle.BackColor = rowColor ;

You are doing it the wrong way. You have to databind your gridview on either page load or a custom event (say click of a button) & not rowDataBound event. This event occurs when your row is bound with data & you want to change some attributes for each row (as in your case).
You can use Gridview DataBound event to assign colors in following way
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Fetch status Id for current row
int statusId= Convert.ToInt32(DataBinder.Eval(e.Row.DataItem,"UnitsInStock"));
switch (statusId)
{
case (1):
e.Row.BackColor= System.Drawing.Color.Green;
break;
// other cases follow the same
}
}
}
Put the databinding code in either pageLoad or button click event.

protected void grdMyQ_RowDataBound(object sender, GridViewRowEventArgs e)
{
for (int i = 0; i < grdMyQ.Rows.Count; i++)
{
if (grdMyQ.Rows[i].Cells[13].Text.ToUpper() == "DISCHARGED_PROCESS")
{
grdMyQ.Rows[i].BackColor = Color.Red;
}
}
}

Related

How to make dynamic column header clickable in gridview

I have a gridview with many columns. It's sortable, Allow Sorting="True", each column has Sort Expression. For each column sorting works just fine, except for 10 columns that have dynamic headers that I assign in Row_Databound event:
protected void gvSearchResults_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
for (int i = 1; i < 11; i++)
{
if (Session["Label" + i.ToString()] !=null)
{
e.Row.Cells[i].Text = Session["Label" + i.ToString()].ToString();
}
}
}
}
These 10 columns are not clickable. Is there any way to make them clickable? Everything else in these columns is enabled for sorting.
I've got some suggestions from a different forum about creating columns in Page_Load or Page_Init events, but this probably won't work for me.
Thank you.
You can replace the text of the existing LinkButton in the header cell:
protected void gvSearchResults_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
for (int i = 1; i < 11; i++)
{
string caption = Session["Label" + i.ToString()] as string;
if (caption != null)
{
TableCell headerCell = e.Row.Cells[i];
LinkButton lnkSort = headerCell.Controls[0] as LinkButton;
lnkSort.Text = caption;
}
}
}
}
It can be done. If you look at the HTML code you will see something similar to this as the link for sorting the GridView.
yourColumnName
We need to recreate that link in the RowDataBound function.
for (int i = 1; i < 11; i++)
{
//first we cast the sender as a gridview
GridView gv = sender as GridView;
//get the unique ID of the gridview, this is different from ClientID which you normally would use for JavaScipt etc
string uniqueID = gv.UniqueID;
//then get the SortExpression for the column
string sortExpression = gv.Columns[i].SortExpression;
//get the new column name from the session
string yourColumnName = string.Empty;
if (Session["Label" + i.ToString()] != null)
{
yourColumnName = Session["Label" + i.ToString()].ToString();
}
//and then we fill the header with the new link
e.Row.Cells[i].Text = "" + yourColumnName + "";
}
However for this to work, enableEventValidation has to be set to false, which is NOT recommended. Otherwise you will get the "Invalid postback or callback argument" error.
Better would be changing the column names somehow before the data is bound to the gridview.
Thank you very much for your help. The solution with LinkButton worked great for me:
protected void gvSearchResults_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
for (int i = 1; i < 11; i++)
{
if (Session["Label" + i.ToString()] !=null)
{
((LinkButton)(e.Row.Cells[i].Controls[0])).Text = Session["Label" + i.ToString()].ToString();
}
}
}
}

Radio Button Dynamically in ASP.net using html.append

I am adding values to html table from a database. What I want is to attach a radio button with each row such that if the user selects a row to be deleted he may do so. I am getting the value of my radio button as vehicle_syskey from the following code and not the numerical value that the variable stores. Below is my code. Please tell me how I can achieve this. Thanks in advance.
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
StringBuilder html = new StringBuilder();
html.Append("<table border=1");
//append headers
//Populating a DataTable from database.
<--Some Relevant Code Present Here>
int vehicle_syskey = 0;
string gm_ymm = null;
foreach (DataRow row in oemTable.Rows)
{
html.Append("<tr>");
vehicle_syskey = Convert.ToInt32(row[0]);
html.Append("<td>");
html.Append("<input type='radio' name='veh_key' class='my_button' value=vehicle_syskey ");
html.Append("</td>");
html.Append("<td>");
html.Append(vehicle_syskey);
html.Append("</td>");
gm_ymm = Convert.ToString(row[1]);
html.Append("<td>");
html.Append(gm_ymm);
html.Append("</td>");
html.Append("<td>");
//Another Query here
foreach (DataRow row1 in vcdbTable.Rows)
{
foreach (DataColumn column1 in vcdbTable.Columns)
{
html.Append(row1[column1.ColumnName]);
html.Append(" ");
}
html.Append("<br>");
}
html.Append("</td>");
}
conn.Close();
//Table end.
html.Append("</table>");
//Append the HTML string to Placeholder.
PlaceHolder1.Controls.Add(new Literal { Text = html.ToString() });
}
}
protected void match1_Click(object sender, EventArgs e)
{
string val = Request.Form["veh_key"].ToString();
Label l1 = new Label();
l1.Text = val;
}

how to get total of all column if GridView Paging is set as “True”?

this code display total of column in each page of grid view footer I want to display total of all columns in all pages footer
if (e.Row.RowType == DataControlRowType.DataRow)
{
string deb = ((Label)e.Row.FindControl("debit")).Text;
string cred = ((Label)e.Row.FindControl("credit")).Text;
decimal totalvalue = Convert.ToDecimal(deb) - Convert.ToDecimal(cred);
amount += totalvalue;
Label lbl = (Label)e.Row.FindControl("lblTotal");
lbl.Text = amount.ToString();
Label lblDebAmount = (Label)e.Row.FindControl("debit");
Label lblCredamount = (Label)e.Row.FindControl("credit");
float debtotal = (float)Decimal.Parse(lblDebAmount.Text);
float credtotal = (float)Decimal.Parse(lblCredamount.Text);
totalPriced += debtotal;
totalPricec += credtotal;
}
if (e.Row.RowType == DataControlRowType.Footer)
{
Label totallblCAmount = (Label)e.Row.FindControl("totallblDebAmount");
Label totallblCredAmount = (Label)e.Row.FindControl("totallblCredAmount");
totallblCAmount.Text = totalPriced.ToString("###,###.000");
totallblCredAmount.Text = totalPricec.ToString("###,###.000");
}
}
Why do it when the row is data bound? Why not do it when you originally bind the data?
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
DataTable dt = Database.GetData();
GridView1.DataSource = dt;
GridView1.DataBind();
//calculate here by manually adding up the debit/credit column from dt
//or do a separate database call that calculates the sum, ex: select sum(debits), sum(credits) from general_ledger
}
}
It makes sense to let the database do the math calculation for you. You wouldn't need to write your own custom calculation code. Just let the database's sum function handle it.
Here's a little more detail.
//Executes a SqlCommand and returns a DataTable
public class GetDataTable(SqlCommand command)
{
var dt = new DataTable();
using (var connection = new SqlConnection("connectionstring"))
{
command.Connection = connection;
connection.Open();
dt.Load(command.ExecuteReader());
}
return dt;
}
//Executes a SqlCommand and returns a scalar of type T
public static T GetScalar<T>(SqlCommand command)
{
using (var connection = new SqlConnection ("connectionstring"))
{
command.Connection = connection;
connection.Open();
var result = command.ExecuteScalar();
if (result is T)
{
return (T)result;
}
else
{
return (T)Convert.ChangeType(result, typeof(T));
}
}
}
//Load the data into the GridView, then get the credit amount and put the value in a label.
//You'll need to adjust the queries to match your schema
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
var tableCommand = new SqlCommand("select columns from table");
GridView1.DataSource = GetDataTable(tableCommand);
GridView1.DataBind();
var creditCommand = new SqlCommand("select sum(stat_amount) from tablename where stat_flag='c'");
var credits = GetScalar<decimal>(creditCommand);
Label1.Text = credits;
}
}

remove previously stored value of a checkbox in a session when user unchecks this checkbox

I try to dynamically create checkboxes - all of them with assigned checkedChanged event.
In the event handler i test if the checkbox is checked and if so I sore the value attribute in a session.
But here occurs a big problem for me.
For example a client decides to check one checkboxes and it's value attribute is added to the session, but then he suddenly decides that he doesn't want that checbox to be checked and he unchecks it - it's ok, but this value will stay stored in the session and I don't eant that.
So is there any way to delete this value when the user unchecks the checkbox
protected void btnProba_Click(objectore sender, EventArgs e)
{
lblProba.Text = ((String)Session["chk"]);
// lblProba.Text = pr.ToString();
}
protected void checkChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
if (chk.Checked)
{
//lblProba.Text += chk.Text;
//myche.Add(chk.Text);
Session["chk"] += chk.InputAttributes["value"];
}
}
protected void ddlNumberTourists_SelectedIndexChanged(object sender, EventArgs e)
{
chkddlchange = true;
int numTourists = Convert.ToInt32(ddlNumberTourists.SelectedItem.Text);
for (int i = 0; i < numTourists; i++)
{
string connectionString = "Server=localhost\\SQLEXPRESS;Database=excursion;Trusted_Connection=true";
string query =
"SELECT Extra_Charge_ID, Excursion_ID, Amout, Extra_Charge_Description FROM EXTRA_CHARGES WHERE Excursion_ID=" + mynewstring;
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(query, conn);
try
{
conn.Open();
SqlDataReader rd= cmd.ExecuteReader();
int s = 0;
while (rd.Read())
{
CheckBox mycheckbox = new CheckBox();
mycheckbox.ID = "chkblextracharge" + i.ToString() + s.ToString();
mycheckbox.Text = rd["Extra_Charge_Description"].ToString();
mycheckbox.InputAttributes.Add("value", rd["Extra_Charge_ID"].ToString());
mycheckbox.AutoPostBack = true;
mycheckbox.CheckedChanged += new EventHandler(checkChanged);
Page.FindControl("form1").Controls.Add(mycheckbox);
}
}//End of try
catch (Exception ex)
{ }
}//end of for
}
}
}
It seems like you store checkboxes values as a concatenated string in Session["chk"]. It makes removing anything from there pretty hard. I guess it might be better to store a list of strings in Session["chk"], so you would be able to easy add/remove entries from there...

Prepopulate gridview empty datasource

I use an gridview empty datasource for bulk insert, how would I prepopulate for instance Column A with the value of a drop down box? So far I have below, but its not working
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
TextBox tb = (TextBox)e.Row.FindControl("YourTextBoxID");
if(tb != null)
{
tb.Text = DropDownList1.SelectedItem.Text;
}
}
}
I don't understand what you mean with empty DataSource. I assume that you actully mean a DataSource which is populated automatically with a default value.
You could use a DataTable:
var tbl = new DataTable();
tbl.Columns.Add("ColumnA");
var defText = DropDownList1.SelectedItem.Text;
for(int i = 0; i < 1000; i++)
{
tbl.Rows.Add(defText);
}
GridView1.DataSource = tbl;
GridView1.DataBind();

Resources