C# 如何仅显示数据表中的某些列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/208186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 18:06:07  来源:igfitidea点击:

How do I display only certain columns from a data table?

c#.netdatagriddatatabledataset

提问by Adyt

I'm using a web service that returns a dataset. in this dataset there are 5 table, let's say table A, B, C, D, E. I use table A.

我正在使用返回数据集的 Web 服务。在这个数据集中有 5 个表,比如表 A、B、C、D、E。我使用表 A。

So

所以

DataTable dt = new DataTable()
dt = dataset.Table["A"]

Now in this datatable there are columns a1,a2,a3,a4,a5,a6,a7.

现在在这个数据表中有列 a1、a2、a3、a4、a5、a6、a7。

Let's say I only want to get columns a3 and a4 then bind it to my datagrid.

假设我只想获取列 a3 和 a4,然后将其绑定到我的数据网格。

How do I do this?

我该怎么做呢?

采纳答案by DOK

Ignore the fact that you have more data than you need. Set AutoGenerateColumnsto false. Create BoundColumnsfor a3and a4.

忽略您拥有的数据多于所需的事实。设置AutoGenerateColumnsfalseBoundColumnsa3和创建a4

回答by Ilya Komakhin

I'd bind the whole table, then set up visibility of the coulmns as follows

我会绑定整个表,然后如下设置 coulmns 的可见性

dgvMain.Columns[ColumnA3_Name].Visible = true;
dgvMain.Columns[ColumnA1_Name].Visible = false;

回答by Vivek

I'd recommend reading thisarticle from 4GuysFromRolla for anyone who needs a good understanding of the DataGridWeb Control.

对于需要深入了解Web 控件的任何人,我建议您阅读4GuysFromRolla 的这篇文章DataGrid

Note: Since this question is already answered. I want to clarify what needs to be done, just in case anyone else is wondering.

注意:因为这个问题已经回答了。我想澄清需要做什么,以防万一其他人想知道。

DataSet ds;

//Get Data
using (SqlConnection connection = new SqlConnection(connectionString))
    {
        // Create the command and set its properties.
        SqlCommand command = new SqlCommand();
        command.Connection = connection;
        command.CommandText = "GetMyData";
        command.CommandType = CommandType.StoredProcedure;

        ds = connection.ExecuteDataSet();
    }
if(ds !=null && ds.Tables.Count > 0)
{
    dg.DataSource = ds.Tables[0];
    // disable autogeneration of columns
    dg.AutoGenerateColumns = false;
    //Hide unecessary columns
    dg.Columns["a3"].Visible = false;
    dg.Columns["a4"].Visible = false;
}

回答by Dominik Ras

You can always try to set DataPropertyName properties of particular columns to match what's in your DataTable. Then bind that DataTable to a BindingSource and bind that binging source to your grid.

您始终可以尝试设置特定列的 DataPropertyName 属性以匹配您的 DataTable 中的内容。然后将该 DataTable 绑定到 BindingSource 并将该绑定源绑定到您的网格。

As long as names of columns in your DataTable match DataPropertyNames of your DataGrid columns, your data grid should display only those matched columns.

只要 DataTable 中的列名称与 DataGrid 列的 DataPropertyNames 匹配,您的数据网格就应该只显示那些匹配的列。

In my example my stred proc does something simle like:

在我的例子中,我的 stred proc 做了一些类似的事情:

ALTER PROCEDURE ps_Clients_Get
AS
BEGIN
    SELECT 
        convert(varchar(2000), path) as [Client Folder], 
        c.description as [Client Name],
        c.* 
    FROM Client c
END 
GO

and my C# code:

和我的 C# 代码:

using (DataTable dt = new DataTable())
{
    using (OdbcConnection cnDsn = new OdbcConnection(cmLocalTrackingDBDSNAME))
    {
        cnDsn.Open();
        using (OdbcCommand cmdDSN = new OdbcCommand())
        {
                  var _with1 = cmdDSN;
                  _with1.Connection = cnDsn;
                  _with1.CommandType = System.Data.CommandType.StoredProcedure;
                  _with1.CommandText = "{ CALL ps_Clients_Get }";
                  using (OdbcDataAdapter adapter = new OdbcDataAdapter())
                  {
                            dt.Locale = System.Globalization.CultureInfo.InvariantCulture;
                            adapter.SelectCommand = cmdDSN;
                            adapter.Fill(dt);
                            bindingSourceDataLocation.DataSource = dt;
                            dataGridViewDataLocation.AutoGenerateColumns = false;

                            dataGridViewDataLocation.DataSource = bindingSourceDataLocation;
                  }
         }
         cnDsn.Close();
    }
}

Good luck!

祝你好运!

回答by lokendra jayaswal

Hi Following code can be used

您好以下代码可以使用

//It represent name of column for which you want to select records
string[] selectedColumns = new[] { "a3", "a4" }; 

DataTable tableWithSelectedColumns = new DataView(dataset.Table["A"]).ToTable(false,  selectedColumns);

I tried this and it works.

我试过这个,它的工作原理。

回答by Chris978

    Dim DT As DataTable = YourDT

    DGV.DataSource = dt
    DGV.AutoGenerateColumns = False

    Dim cc = DGV.ColumnCount

    For i = 0 To cc - 1
        DGV.Columns(i).Visible = False
    Next

    DGV.Columns("ColumnToShow").Visible = True
    DGV.Columns("ColumnToShow").Visible = True