I have a gridview control which contains an image field. However, the image url is built from several fields in my returned dataset. How do you concatenate those fields together, and at which point do I do this so that I can pass that image url do my imagefield in my gridview? I am guessing it's on the RowDataBound but I don't know how to access each of the rows in my dataset?
Thanks.
I'm not sure what you are trying to concatenate without a code example, however I would perform the concatenation before binding the gridview and store it in a private member on the class so that you can access it later in the RowDataBound event.
You can use the row data bound event to find the control within that row and set its ImageUrl property.
private string m_ConcatUrl;
protected void gridView_RowDataBound(Object sender, GridViewRowEventArgs args)
{
if(args.Row.RowType == DataControlRowType.DataRow)
{
Image imgCtrl = (Image) args.Row.FindControl("imgCtrl");
imgCtrl.ImageUrl = m_ConcatUrl;
}
}
You can use RowDataBound event to set the cell value.
void YourGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// You can set your cell value in this
e.Row.Cells[index] // use this to set the value in the cell
}
}
In .NET 4, it would be like this:
if (e.Row.RowType == DataControlRowType.DataRow)
{
string1 = e.Row.Cells[i].Text;
}
i is the index of the particular column you want to reference (e.g. Cells[0] is column 1).
I'm not sure if it's different in 3.5 but try that.
Related
I have a datatable that I bind to a gridview. The columns are variable so I'd like to take advantage of AutoGeneratedColumns. I'd like to bind an image in certain condtions. What do I need to do?
void GridView1_RowCreated(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
DataRowView drv = e.Row.DataItem as DataRowView;
if (drv != null)
drv[1] = new HtmlImage() { Src = "add.png" };
}
It sounds like the AutoGeneratedColumns property won't help you here because column types apply to the whole GridView; they are not calculated per-row.
You might be able to use a TemplateField with databinding to conditionally format the field for each row without writing any code.
If that doesn't get it done for you, I suppose you will have to write code. Bear in mind that the RowCreated event always fires (event on postback) when a row is created, but will only give you a non-null DataItem (e.Row.DataItem) when the GridView actually goes to its DataSource for databinding; if the GridView has cached its rendered state (in ViewState), the data item will be null. At that point, you would only be able to access the row's primary key fields by doing something like this: var keys = myGridView.DataKeys[rowIndex]; (The primary key fields are determined by the value you give the GridView's DataKeyNames property, and are stored in ViewState so that you can access them on postback.)
You would also be careful when modifying a column that is some type of DataBoundField (as most Fields are); since the RowDataBound event happens after the RowCreated event, any manual changes to the content of a row/cell you make in the RowCreated event handler are going to be clobbered by databinding when RowDataBound is fired.
That said, RowDataBound is probably the event you want.
The RowDataBound event will always give you a non-null DataItem, but only fires when real databinding happens (as opposed to "binding" from ViewState); so typically this event does not fire at all on postbacks. That's OK, though, since the GridView will remember its state for you.
If you must use code, it should probably look something like this:
//don't forget to attach this event handler, either in markup
//on the GridView control, in code (say, in the Page_Init event handler.)
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
//HtmlImage gives you a plain-vanilla <img> tag in the HTML.
//If you need to handle some server side events (such as Click)
//for the image, use a System.Web.UI.WebControls.Image control
//instead.
HtmlImage img = new HtmlImage() { Src = "path/to/image.jpg" };
e.Row.Cells[1].Controls.Add(img);
}
But, seriously, check out TemplateField first.
You can use RowDataBound event to process each row:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView drv = e.Row.DataItem as DataRowView;
if (drv != null)
{
// your code here...
}
}
}
For more information about this event see here
This should work, it uses the controls of the actual cell:
void GridView1_RowCreated(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
HtmlImage img = new HtmlImage() { Src = "add.png" };
e.Row.Cells[1].Controls.Add(img);
}
First of all, I am a new C# developer and I need some help please, I have a grid view with its SqlDataSource in my aspx file that contains 3 columns ID/Name/Job and several records(rows). When the user selects a row, I would like to redirect to another page and pass as a parameter the value of the selected ID of the row. Users are permitted to select only one row each time. I spent several hours on that however something strange is happened.
I have a method
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
string selectedID;
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridViewRow gvr = e.Row;
selectedID = (GridView1.DataKeys[e.Row.RowIndex].Value.ToString());
gvr.Attributes.Add("OnClick","javascript:location.href='Views/EditMenus/EditCompany.aspx?id=" + selectedID + "'");
gvr.Attributes.Add("onmouseover", "this.style.backgroundColor='#FFE6E6'");
gvr.Attributes.Add("onmouseout", "this.style.backgroundColor=''");
gvr.Attributes.Add("style", "cursor:pointer;");
Session["IDs"] = selectedID;
} }
In my redirect page I have in page load method the following code:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["IDs"] != null)
{
Label2.Text = "Selected ID is: "+ Session["IDs"].ToString();
}
}
Now, when I select a row, the redirection to the other page works correctly and the browser url has the correct value of the selected ID according the javascript code above, however the Label2.Text prints a wrong ID. Instead of the value of the selected ID, it prints the value ID of the last row of each page. Why that happens?
It's a bit strange for me since I am using the same variable "selectedID" for both cases as you can see above.
You need to sore value of your ID in Session variable on SelectedIndexChanged event of your GridView
void CustomersGridView_SelectedIndexChanging(Object sender, GridViewSelectEventArgs e)
{
// Get the currently selected row.
//Because the SelectedIndexChanging event occurs before the select operation
//in the GridView control, the SelectedRow property cannot be used.
//Instead, use the Rows collection
//and the NewSelectedIndex property of the
//e argument passed to this event handler.
GridViewRow row = CustomersGridView.Rows[e.NewSelectedIndex];
//Cells[0] is for first column so assign according to your column for ID
Session["IDs"]=row.Cells[0].Text;
}
I have a sqldatasource and gridview.
I have two columns:
ID | Status
1 Closed
2 Opened
3 Waiting
How to change the color of the label in the view state of the gridview depeding on the value from the 'status' column.
For example if the value in the cell is "Closed" the label color will be red , if it's opened then it will become green and so on.
I've thought about looping through all cells of the status column and if the cell contains a certain value the color will change. ( in row data bound event ) . But I haven't done this because I don't find this idea as a good one because of the looping part.
use the RowDataBound event from the grid view to check what is the status. You don't need to do a loop because that event (if you register or not) is being called.
One thing to note, you will need to make sure you are looking at the right row (header, footer, alternate etc) so something like this
void YourGridViewName_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Do your color change here by accessing the col with e.Row.Cells[column_index].BackColor = 'what ever you want'
}
}
You can enable the RowDataBound Event in the markup
<asp:GridView ID="gridview1" runat="server" OnRowDataBound="RowDataBound">
</asp:GridView>
And put this in your Code-Behind file.
protected void RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Retrieve the underlying data item. In this example
// the underlying data item is a DataRowView object.
DataRowView rowView = (DataRowView)e.Row.DataItem;
// Retrieve the state value for the current row.
String state = rowView["state"].ToString();
//format color of the as below
if(state == "Closed")
(e.Row.FindControl("lbl1") as Label).BackColor = Color.Red;
if(state == "Open")
(e.Row.FindControl("lbl1") as Label).BackColor = Color.Green;
if(state == "Waiting")
(e.Row.FindControl("lbl1") as Label).BackColor = Color.Yellow;
}
}
You have to write code in the rowdatabound event of your grid view.
Example:
private GridView1_RowDatabound(object sender,EventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// You have to put your logic here.
if( e.Row.Cells[1].Text == "closed" )
{
// to get a reference to label control
Label lb = e.Row.FindControl("LabelCOntrolID");
}
}
}
Note: i need to change in different columns based upon search request.
Yes you can do it in GridView.RowDataBound event
Like this
protected void yourGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].BackColor = Color.Beige;
// 0 could be any valid cell index in your row
}
}
for more info Go here
I have a GridView on my webpage whose DataSource is a DataTable which is populated at runtime. AllowSorting property of GridView is True. I have successfully implemented manual sorting for this GridView.
But I had to translate the webpage to other languages for which I used local resource files. I changed the Header text of GridView columns in RowDataBound event. Since then I'm unable to sort the GridView.
protected void GVSummaryTable_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.Cells.Count > 0)
{
//Translate header text
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Text = GetLocalResourceObject("GVSummaryTableName").ToString();
e.Row.Cells[1].Text = GetLocalResourceObject("GVSummaryTableLoginLevel").ToString();
e.Row.Cells[2].Text = GetLocalResourceObject("GVSummaryTableLoginID").ToString();
e.Row.Cells[4].Text = GetLocalResourceObject("GVSummaryTableDate").ToString();
}
}
}
What should I do to enable sorting for the columns?
Any help would be appreciated. Thanks!
Changing the code to below solved the problem:
if (e.Row.RowType == DataControlRowType.Header)
{
LinkButton LnkHeaderText = e.Row.Cells[1].Controls[0] as LinkButton;
LnkHeaderText.Text = "Name";
}
I am not sure if the problem is related to the Header text since the sorting is normally done with the Sort Expression. Please, make sure you are also giving a value to this property when doing the Sorting. Hope this helps!