Change DataField Attribute in a Gridview dynamically - c#

I have a GridView like this:
<asp:GridView ID="GridViewAllPeopleEditMode" runat="server"
AutoGenerateColumns="false"
AutoGenerateEditButton="true"
AllowPaging="true"
PageSize="20"
OnRowEditing="GridViewAllPeopleEditMode_RowEditing"
OnRowCancelingEdit="GridViewAllPeopleEditMode_RowCancelingEdit"
OnRowUpdating="GridViewAllPeopleEditMode_RowUpdating"
OnPageIndexChanging="GridViewAllPeopleEditMode_PageIndexChanging">
<Columns>
<asp:BoundField DataField="id" HeaderText="BusinessEntityID" ReadOnly="true"/>
<asp:BoundField DataField="FirstName" HeaderText="FirstName"/>
<asp:BoundField DataField="MiddleName" HeaderText="MiddleName"/>
<asp:BoundField DataField="LastName" HeaderText="LastName"/>
</Columns>
</asp:GridView>
I want the page_load to set the DataField attributes before setting the DataSource()/DataBind(), instead of writing them by myself in the .aspx page.
Is it possible to do that, or do I have to change the BoundFields?
Thanks a lot!

You can use like this in code side
C#
BoundField field = (BoundField)this.GridViewAllPeopleEditMode.Columns[0];
field.DataField = "To";
VB
Dim field As BoundField = DirectCast(Me.GridViewAllPeopleEditMode.Columns(0), BoundField)
field.DataField = "To"

Related

Grid view footer not showing

I am building a gridview from an arraylist and want to include a footer to the bottom.
This is my c# code
gvOrder.DataSource = orderItemList;
gvOrder.DataBind();
gvOrder.ShowFooter = true;
gvOrder.Columns[0].FooterText = "Totals:";
gvOrder.Columns[2].FooterText = Convert.ToString(quantity);
gvOrder.Columns[4].FooterText = Convert.ToString(priceTotal);
Here is my asp code
<asp:GridView ID="gvOrder" runat="server" AutoGenerateColumns="False" ShowFooter="True">
<Columns>
<asp:BoundField DataField="ItemTitle" HeaderText="Title" />
<asp:BoundField DataField="ItemFormat" HeaderText="Format" />
<asp:BoundField DataField="ItemQuantity" HeaderText="Quantity" />
<asp:BoundField DataField="ItemPrice" HeaderText="Price" />
<asp:BoundField DataField="ItemTotal" HeaderText="Total" />
</Columns>
</asp:GridView>
The order of things matter. You have to set the footer values before DataBind() is called.
gvOrder.Columns[0].FooterText = "Totals:";
gvOrder.Columns[2].FooterText = Convert.ToString(quantity);
gvOrder.Columns[4].FooterText = Convert.ToString(priceTotal);
gvOrder.DataSource = orderItemList;
gvOrder.DataBind();
gvOrder.ShowFooter = true;
But you can set the values of the Footer Row after DataBind if you specify the footerrow cells instead of the Colums.
gvOrder.FooterRow.Cells[1].Text = "After DataBind";

Selected Index Changed return null values on a populated Grid View

I have a function that checks which sql query needs to be executed and return a DataTable, it is called searchData and is inside the CarsDataSet class
DataTable dataTable = null; //before there is code to detect the sql command to execute
if (sqlCommand != null)
{
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand, con);
dataTable = new DataTable();
sqlDataAdapter.Fill(dataTable);
}
return dataTable;
I am using then, this function on a aspx.cs page in order to bind this DataTable to a GridView..
GridViewCarsFiltered.DataSource = carsDataSet.searchData(type, manufacturer, maxPrice, minPrice, maxYear, minYear);
GridViewCarsFiltered.DataBind();
The GridView gets populated normally, but the problem comes when a try to get values of a row using an select index changed handler..
protected void GridViewCarsFiltered_SelectedIndexChanged(object sender, EventArgs e)
{
string carId = GridViewCarsFiltered.SelectedRow.Cells[1].Text;
}
I am receiving an 'ArgumentOutOfRangeException' saying that carId is null.
This is my GridView, the DataSourceID is null because I am setting that from code behind..
<asp:GridView ID="GridViewCarsFiltered" runat="server" CssClass="table table-striped table-hover" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2" DataSourceID="" ForeColor="Black" OnSelectedIndexChanged="GridViewCarsFiltered_SelectedIndexChanged" DataKeyNames="Id">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="Id" HeaderText="Id" InsertVisible="False" ReadOnly="True" SortExpression="Id" />
<asp:BoundField DataField="type" HeaderText="type" SortExpression="type" />
<asp:BoundField DataField="manufacturer" HeaderText="manufacturer" SortExpression="manufacturer" />
<asp:BoundField DataField="model " HeaderText="model " SortExpression="model " />
<asp:BoundField DataField="colour" HeaderText="colour" SortExpression="colour" />
<asp:BoundField DataField="price" HeaderText="price" SortExpression="price" />
<asp:BoundField DataField="year" HeaderText="year" SortExpression="year" />
<asp:BoundField DataField="location" HeaderText="location" SortExpression="location" />
<asp:BoundField DataField="username" HeaderText="username" SortExpression="username" />
</Columns>
</asp:GridView>
And this is a screenshot of the actual populated GridView
enter image description here
I hope I've been clear enough and that some of you can help me...
Thank you in advance
The preferred way to retrieve a value in this kind of situation is to use DataKeyNames instead of getting the value from the cell itself. This method can also be used to get values from fields that are not displayed in the columns of the GridView.
You can add the Id field to that attribute in the markup:
<asp:GridView ID="gv" runat="server" DataKeyNames="Id" ... >
and retrieve the value in code-behind this way:
protected void gv_SelectedIndexChanged(object sender, EventArgs e)
{
int carId = (int)gv.DataKeys[gv.SelectedRow.RowIndex].Values["Id"];
}
Note: I used gv instead of GridViewCarsFiltered only to reduce the width of the code samples.
UPDATE
On the other hand, if the GridView is empty after selecting the row, the problem could be that the ViewState is disabled (at the page level or in Web.config). Enabling it should resolve the issue.

Empty column shows when using Hiddenfield in GridView

I have a HiddenField in my GridView. A very small empty column appears, how can I get rid of the empty column?
<asp:GridView ID="GridView1" autogeneratecolumns="false" runat="server"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
autogenerateSelectButton="true">
<Columns>
<asp:BoundField datafield ="Song" headertext="Song"/>
<asp:BoundField datafield ="Album" headertext="Album"/>
<asp:BoundField datafield ="Artist" headertext="Artist"/>
<asp:BoundField datafield ="Genre" headertext="Genre"/>
<asp:BoundField datafield ="Price" headertext="Price"/>
<asp:BoundField datafield ="Explicit Lyrics" headertext="Explicit Lyrics"/>
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="HiddenField" runat="server" Value='<%# Eval("SongID")%>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here is the output
I think you added that hidden field to get id later. No need to add and hide a column. Use datakey .
TemplateField in GridView is meant to represent a field that displays custom content in a data-bound control and HiddenField used to store a non-displayed value.
You are creating a custom content column with a non-displayed value ,that leads to create a column with null as represented view for Front end. So If you want to fetch the value on selected index change of GridView then may use Following methods:
Method1: Use Datakey for grideview to store the datacolumn you want in your selecetedIndexchanged method:
<asp:GridView ID="GridView1" autogeneratecolumns="false" runat="server"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
autogenerateSelectButton="true" DataKeyNames="SongID">
<Columns>
<asp:BoundField datafield ="Song" headertext="Song"/>
<asp:BoundField datafield ="Album" headertext="Album"/>
<asp:BoundField datafield ="Artist" headertext="Artist"/>
<asp:BoundField datafield ="Genre" headertext="Genre"/>
<asp:BoundField datafield ="Price" headertext="Price"/>
<asp:BoundField datafield ="Explicit Lyrics" headertext="Explicit Lyrics"/>
</Columns>
</asp:GridView>
To access that key on SelectedIndexChanged Method :
int songId= Convert.ToInt32(GridView1.DataKeys[GridView1.SelectedIndex].Values);
Method2: Add hiddenfield within any column you have in your gridview not a special one for it.
<asp:GridView ID="GridView1" autogeneratecolumns="false" runat="server"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
autogenerateSelectButton="true">
<Columns>
<asp:BoundField datafield ="Song" headertext="Song"/>
<asp:BoundField datafield ="Album" headertext="Album"/>
<asp:BoundField datafield ="Artist" headertext="Artist"/>
<asp:BoundField datafield ="Genre" headertext="Genre"/>
<asp:BoundField datafield ="Price" headertext="Price"/>
<asp:TemplateField headertext="Explicit Lyrics" >
<ItemTemplate>
<asp:Lable runat="server" ID="lblexp" Text='<%# Eval("Explicit Lyrics")%>'>
<asp:HiddenField ID="HiddenField" runat="server" Value='<%# Eval("SongID")%>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You could add this:
<style>
.hidden {display:none;}
</style>
And adding these properties to the asp:HiddenField or ItemTemplate element
ItemStyle-CssClass="hidden" and
HeaderStyle-CssClass="hidden :) let me know if it worked.
You can set the CellPadding and CellSpacing attributes of the GridView to zero:
<asp:GridView CellPadding="0" CellSpacing="0" ... >
If you still see the column you can set its width to zero:
<asp:TemplateField ItemStyle-Width="0" HeaderStyle-Width="0" ... >
On Gridview RowDataBound function add the below code to hide the columns you want.
Eg:
In the aspx,
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound">
In code behind,
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[cellno.].Visible = false;
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[cellno.].Visible = false;
}
}

How to fetch primary key in GridView but don't display it?

Using <asp:GridView></asp:GridView> I am trying to display columns of database table. I want to fetch primary key of table but obviously don't want to display it. How can I achieve this?
This is my GridView
<asp:GridView ID="MyGrid" runat="server" BorderColor="#0066FF" AllowPaging="false" PageSize="5" AllowSorting="true" AutoGenerateColumns="false"
AutoGenerateEditButton="true" OnRowEditing="MyGrid_RowEditing" AutoGenerateDeleteButton="true" OnRowDeleting="MyGrid_RowDeleting"
OnRowDataBound="MyGrid_RowDataBound" EmptyDataText="No Value" BorderWidth="0px" BorderStyle="Solid">
<Columns>
<asp:BoundField DataField="PrimaryKey" HeaderText="UserId"/>
<asp:BoundField DataField="Column1" HeaderText="Column1" />
<asp:BoundField DataField="Column2" HeaderText="Column2" />
<asp:BoundField DataField="Column3" HeaderText="Column3" />
</Columns>
</asp:GridView>
I also tried visible=false to hide primary key, it hides primary key from displaying but also don't fetch its value and I want this value.
Hope my question is clear.
You need to set Visible = false within the OnRowDataBound event, this will mean the data is still accessible to you, but won't display on the page.
<asp:GridView ID="MyGrid" runat="server" BorderColor="#0066FF"
AllowPaging="false" PageSize="5" AllowSorting="true"
AutoGenerateColumns="false" AutoGenerateEditButton="true"
OnRowEditing="MyGrid_RowEditing" AutoGenerateDeleteButton="true"
OnRowDeleting="MyGrid_RowDeleting"
OnRowDataBound="MyGrid_RowDataBound" EmptyDataText="No Value"
BorderWidth="0px" BorderStyle="Solid">
<Columns>
<asp:BoundField DataField="PrimaryKey" HeaderText="UserId"/>
<asp:BoundField DataField="Column1" HeaderText="Column1" />
<asp:BoundField DataField="Column2" HeaderText="Column2" />
<asp:BoundField DataField="Column3" HeaderText="Column3" />
</Columns>
</asp:GridView>
In Codebehind:
protected void MyGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[0].Visible = false;
}
<asp:GridView ... DataKeyNames="PrimaryKey" />
You can use this:
<asp:BoundField DataField="PrimaryKey" visible="false" HeaderText="PKId"/>
Also use this
<asp:BoundField DataField="PrimaryKey" visible="false" HeaderText="UserId"/>
To get Primary Key
<asp:GridView ID="MyGrid" runat="server" BorderColor="#0066FF" DataKeyNames="PrimaryKey"
MyGrid.DataKeys[e.NewEditIndex].Value
OR
MyGrid.Rows[e.NewEditIndex].DataBoundItem
If you want to hide a column by its name instead of its index in GridView. After creating DataTable or Dataset, you have to find the index of the column by its name then save index in global variable like ViewStae, Session and etc and then call it in RowDataBound, like the example:
string headerName = "Id";
DataTable dt = .... ;
for (int i=0;i<dt.Columns.Count;i++)
{
if (dt.Columns[i].ColumnName == headerName)
{
ViewState["CellIndex"] = i;
}
}
... GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header || e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Footer)
{
int index = Convert.ToInt32(ViewState["CellIndex"]);
e.Row.Cells[index].Visible = false;
}
}

Accessing data from a BoundField of Gridview

I have a GridView like this
<asp:GridView ID="gv_FilesList" runat="server" AutoGenerateColumns="false" onrowcommand="gv_FilesList_RowCommand">
<Columns>
<asp:BoundField DataField="f_Id" Visible="false" HeaderText="File Name" />
</Columns>
<Columns>
<asp:BoundField DataField="f_Name" HeaderText="File Name" />
</Columns>
<Columns>
<asp:ButtonField ButtonType="Link" Text="Download" CommandName="DownloadFile" HeaderText="Download" />
</Columns>
</asp:GridView>
Now when I click on the download Button, how can I get the corresponding f_Id in order to get the related data from Database.
This code should work, tested on my local.
First, add DataKeyNames to your GridView.
<asp:GridView ID="gv_FilesList" runat="server" AutoGenerateColumns="false" onrowcommand="gv_FilesList_RowCommand" DataKeyNames="f_Id">
<Columns>
<asp:BoundField DataField="f_Id" Visible="false" HeaderText="File Name" />
</Columns>
<Columns>
<asp:BoundField DataField="f_Name" HeaderText="File Name" />
</Columns>
<Columns>
<asp:ButtonField ButtonType="Link" Text="Download" CommandName="DownloadFile" HeaderText="Download" />
</Columns>
</asp:GridView>
Then, access DataKeys from codebehind.
protected void gv_FilesList_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DownloadFile")
{
//row index
int index = Convert.ToInt32(e.CommandArgument);
//retrieve f_Id
int f_Id = Convert.ToInt32(gv_FilesList.DataKeys[index].Value);
//download file with f_Id
DownloadFile(f_Id);
}
}
A couple of ways to skin it, but you could access it like below:
void gv_FilesList_RowCommand(Object sender, GridViewCommandEventArgs e) {
if(e.CommandName=="DownloadFile")
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gv_FilesList.Rows[index];
string fileDownloadId = row.Cells[1].Text;
//Pull from DB
}
And then add f_id, to the DataKeyNames attribute so it will store the hidden fields value.
<asp:GridView ID="gv_FilesList" runat="server" AutoGenerateColumns="false" onrowcommand="gv_FilesList_RowCommand" DataKeyNames="f_id">
DataKeyNames
A solution to your problem is described in this thread.
Basically you can access the row index in the event argument property called CommandArgument.

Categories

Resources