ASP.net programmatically associates a dataset with a gridview

I have a dataset with about 15 columns, and I also have an ASP.net view grid. I was wondering if anyone knows how I can fill a grid with a dataset, but the problem is that I just want some columns from the dataset.

at the moment I'm just doing

GridView1.DataSource = ds; GridView1.DataBind(); 

but this obviously connects all the columns from the dataset to the grid view.

+6
source share
5 answers

So you want to create columns at runtime? Try the following:

http://www.codeproject.com/KB/aspnet/dynamic_Columns_in_Grid.aspx

Alternatively, you can pre-configure gridview in aspx:

 <Columns> <asp:BoundField DataField="ProductName" HeaderText="Product" SortExpression="ProductName" /> <asp:BoundField DataField="CategoryName" HeaderText="Category" ReadOnly="True" SortExpression="CategoryName" /> <asp:BoundField DataField="UnitPrice" DataFormatString="{0:c}" HeaderText="Price" HtmlEncode="False" SortExpression="UnitPrice" /> </Columns> 

And make sure you set AutoGenerateColumns to false.

+10
source

GridView by default will automatically generate all columns based on the attached data.

Set GridView.AutoGenerateColumns = false , and then define the required columns using the GridView.Columns property.

+7
source

Two ways I can do this, depending on what you can change and what should remain as it is:

1) If you have control over the / proc query that generates a dataset and can do this without harming other grids / pages, modify the query so that it only selects the columns to use. You can still use unselected columns in JOIN and WHERE, and you get an extra bonus without adding each column to ORDER BY.

2) If you only have control over the grid and code code that were used to create it, you can set AutoGenerateColumns = false as the DataGrid parameter and then attach to your DataGrid, BoundFields, which you need to show. It also allows you to format, create column names, etc.

If you can do both of these things, your grid should also load faster.

+2
source

Set the AutoGeneratedColumns grids to false and set the columns you want to use in the gridview designer or in the code. But you have to set the DataField property in the column just like the name

+1
source
 SqlCommand comm = new SqlCommand("Select required fields from YourTable, conn); conn.Open(); SqlDataReader rdr = comm.ExecuteReader(); GridView1.DataSource = rdr; GridView1.DataBind(); rdr.Close(); 

Only the required fields will be printed.

0
source

Source: https://habr.com/ru/post/890606/


All Articles