I looked around for answer about my problem already, but I gig not find anything conclusive. I Want to to the following:
I have an asp.net form with a GridView which is not bound to a data source which hence does not have pre-defined columns. I populate the gridview with data from an SQL Server dynamically:
gvComponentLocks.DataSource = getComponentsAndLocks(worksPermitID);
//Note getComponentsAndLocks encapsulates the database query and returns a DataTable
gvComponentLocks.DataBind();
Now I want to have a DropDownList in one specific column of the GridView. This DropDownList shall be populated with values dynamically (here I think the ...Item.Add is the appropriate approach).
My biggest problem is how to create the DropDownLists in the cells without being able to define them statically as asp:TemplateField in the web page's markup?
Another way to answer my question would be how to populate a statically defined GridView (with statically defined DropDownList control) dynamically with data from a data source - without the need to bind the GridView statically to a DataSource.
You can create the DropDownList dynamically in the RowDataBound event of the GridView.
protected void gvComponentLocks_RowDataBound(object sender, GridViewRowEventArgs e)
{
//check if the row is a datarow
if (e.Row.RowType == DataControlRowType.DataRow)
{
//create a new dropdownlsit
DropDownList ddl = new DropDownList();
//bind the source and define the values
ddl.DataSource = getComponentsAndLocks(worksPermitID);
ddl.DataTextField = "columnA";
ddl.DataValueField = "columnB";
ddl.DataBind();
//add the dropdownlist to the gridview in column 1
e.Row.Cells[1].Controls.Add(ddl);
}
}
The only thing you also have to do is to place the DataBBinding of the GridView outside the IsPostBack check. Otherwise you'll lose the DropDowns after a PostBack.
Assuming GridView (with statically defined DropDownList control)
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
In side
protected void gvComponentLocks_RowDataBound(object sender, GridViewRowEventArgs e)
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
do something like...
DropDownList DropDownList1 = (DropDownList)e.Row.FindControl("DropDownList1");
DropDownList1.DataSource=SomeDropDownList1ItemCollection
DropDownList1.Bind();
Alternatively return from a ListItemCollection, preferably...
gvComponentLocks.Items.AddRange(LoadList().Cast<ListItem>().ToArray());
where
public ListItemCollection LoadList()
{
ListItemCollection Items = new ListItemCollection();
Items.Add(new ListItem("Choose from list...", ""));
Items.Add(new ListItem("Text","Value")
Dynamic DropDownList:
Put a PlaceHolder Control in the Template in the Grid. Create a DropDownList control with appropriate ids in the code behind and add to the PlaceHolder control.
DropDownList DropDownList1= new DropDownList();
DropDownList1.ID=...
etc
YourPlaceHolderControl.Controls.Add(DropDownList1)
You will have to build back this dynamic DropDownList on postback and repopulate it.
I know this type of question is asked before but no one got the answer yet...!!
How to get a Grid View Row from Data Keys.I don't want to iterate through the whole gird view.
I want to access specific text box(s) in a grid view.
for example in a 100 rows grid view i only want to disable any 2 text boxes on Page Load.
I have Data Key Names defined in grid, but how to get rows from it ?
any idea?
Please try following code..
protected void GVSample_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Get data row view
DataRowView drview = e.Row.DataItem as DataRowView;
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find textbox control
TextBox txtname = (TextBox)e.Row.FindControl("txtName");
string Name = txtname.Text;
if (((GridView)sender).DataKeys[e.Row.RowIndex].Value.ToString() == "Leave")
{
txtname.disable=true;
}
else
{
txtname.disable = false;
}
}
}
I am a new ASP.NET developer. I am using a DetailsView now to dispaly some data from the database. I have the need to highlight certain two rows from the DetailsView. Both rows are VARCHAR data type.
SO HOW TO DO THAT?
Override the databound event and set the e.Row.BackColor = System.Drawing.Color.Red; or what ever color, if you have some logic to execute for finding the row that needs to be highlighted.
protected void detailsView_RowDataBound(object sender,
GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if(...)//some condition for selection of row to be higlighted
{
e.Row.BackColor = System.Drawing.Color.Red;
}
}
}
If you need a perticular row, say 4th row to be highlighted and that's fixed then you could directly like this
detailsViewGrid.Rows[3].Row.BackColor = System.Drawing.Color.Red;
The only thing you need to keep in mind that this code would be written in only those events which would come after grid_rowdatabound event(Like pre-render)
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!
I have an ASP.NET 2.0 (C#) web app, and in it I have a gridview that gets its data from an oracle database.
I want to know how to check if the gridview is empty, and the do something.
I have already tried:
if(GridView.Rows.Count == 0)
{
// Do Something
}
but it doesn't work...
Any ideas?
Thank you.
Your code should work. But only after GridView.DataBind() has been called. Generally I don't check the GridView it's self, but the datasource of the grid view.
DataTable data = DAL.getdata();
if (data.Rows.Count == 0)
{
ShowEmptyData();
}
else
{
Grid.DataSource = dt;
Grid.DataBind();
}
This doesn't work since the GridView is data bound and is going to fetch the actual data at a later time while rendering the page. You should check this by directly querying the data binding source of the gridview (see if the actual list that's grid view bound to is empty or not).
If you just want to display something when it's empty, you should use <EmptyDataTemplate> in your markup:
<asp:GridView runat="server">
<EmptyDataTemplate>The grid is empty</EmptyDataTemplate>
</asp:GridView>
I agree with the other responses. I want to add little information, you should get rows.count after databind method :
int rowCount = GridView.Rows.Count; // returns zero
GridView.DataBind();
rowCount = GridView.Rows.Count; // returns actual row count
If you're using databinding, the the row count of the datasource not the count on the grid itself.
Its very easy: Hope it works for you.. :)
Use event of GridView DataBound: which fires after data is bound.
protected void GridView1_DataBound(object sender, EventArgs e)
{
int rowCount = GridView1.Rows.Count;
if (rowCount == 0)
{
GridView1.Visible = false;
}
else
{
GridView1.Visible = true;
}
}
First create a helper class.
public static class GridViewExtensions
{
public static IEnumerable<GridViewRow> AsEnumerable(this GridView grid)
{
foreach (GridViewRow row in grid.Rows)
{
yield return row;
}
}
public static bool IsEmpty(this GridView grid)
{
return !grid.AsEnumerable().Any(t => t.RowType == DataControlRowType.DataRow);
}
}
Then just call IsEmpty
GridView1.IsEmpty()
In case you've configured your GV to automatically fetch the data from DB, then you may add the following line as the first statement of your GV in Source mode:
<EmptyDataTemplate>No data found.</EmptyDataTemplate>
And then continue with the normal code in your GV.
Based on answers already, GridView.Rows.Count is not enough on its own, depending on the nature of your GridView, especially if it's a dynamic gv, which in most cases it is, plus you have to factor in Paginating, Headers and Footers, which alter the row count.
I use a simple method to tell me ...
//checks if a gridview has any actual rows of data (not just blank rows filled in by the Load
protected bool gvNoData(GridView gv)
{
int wsDataRow = 0;
foreach (GridViewRow gvRow in gv.Rows)
if (gvRow.RowType == DataControlRowType.DataRow)
{
HiddenField hf = (HiddenField)gvRow.FindControl("hfStudentID");
if (hf != null)
if (hf.Value.ToString().Length > 0)
wsDataRow +=1;
}
//if a count was generated then there are data rows, otherwise the rows are blank or nonexistant
if (wsDataRow > 0) return false;
else return true;
}
So running something like this will tell you if the Rows are really "
"DATA" rows, or empty or nothing!
Obviously in my case I have a HiddenField to tell me if the GridViewRow is an actual data row, as I prefill my gridview with blank rows (for my purposes) and some datarows.
However, a simpler version to check based on DataRow vs HeaderRow, etc...
foreach (GridViewRow gvRow in myGridView.Rows)
if (gvRow.RowType == DataControlRowType.DataRow)
{
//do what you need
}
I hope this helps.
In short, there is no GridView.IsEmpty() function unfortunately, unless you enumerate one as shown below.