Reputation: 47
Hi I want to bind my gridview from a datatable which I create myself.
It's works but my columns are duplicated, I don't understand exactly why.
Here is my gridview :
<asp:GridView runat="server" ID="GvCalculSelect" CssClass="gridView" HorizontalAlign="Center">
<Columns>
<asp:BoundField DataField="CalculName" HeaderText="CalculName" />
<asp:TemplateField HeaderText="ResultValue">
<ItemTemplate>
<asp:CheckBox ID="CbResultValue" runat="server" Checked='<%# Convert.ToBoolean(DataBinder.Eval(Container.DataItem, "ResultValue").ToString()) %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And here it's a part of my cs code :
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindGrid();
}
}
protected void BindGrid()
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("CalculName", typeof(string)));
dt.Columns.Add(new DataColumn("ResultValue", typeof(Boolean)));
dt.Rows.Add("Test", true);
GvCalculSelect.DataSource = dt;
GvCalculSelect.DataBind();
}
How to fix it ? I think when I bind my gridview is taking on board my two "dt.columns.add". I just want to keep my calculName field and my resultValue checkbox
Thanks for your help
Upvotes: 1
Views: 1710
Reputation: 1578
This is because GridView.AutoGenerateColumns Property
You need to set its value false.
For your refrence according to MSDN
If you set this property to true and set the ItemType property to a model type, DynamicField controls are generated.
If you do not set the ItemType property, BoundField controls are generated. If you do not want DynamicField controls, you have the following options:
Set the ColumnsGenerator property to null in the Page_Load event handler. In that case, BoundField controls are generated.
Write custom code to automatically generate fields by creating and assigning your own ColumnsGenerator class and assigning an instance of it to the control.
Set AutoGenerateColumns to false. In that case, no fields are generated, and you must manually specify fields using controls such as BoundField or ImageField.
Do not set the ItemType property. In that case, BoundField controls are generated.
Upvotes: 1
Reputation: 5156
This is happening because you are creating your own table and binding it to the GridView AS WELL AS defining 2 columns explicitly in the Gridview and binding datafields to them.
Do 1 or the other, but not both. So, to be clear if you want to control the look and feel of your columns you should set the autogeneratecolumns
property to false. Keep your front end bound columns, but you can then remove them from the datatable and simply reference the relevant fields that are present in the datatable.
Alternatively, set autogeneratecolumns
to true, but then construct the columns in your datatable in your code behind and then just bind it as is.
Upvotes: 2