select certain columns of a data table

后端 未结 6 679
鱼传尺愫
鱼传尺愫 2020-12-09 09:20

I have a datatable and would like to know if its possible for me to select certain columns and input the data on a table. the columns are set out as below

|col1 |col

6条回答
  •  时光取名叫无心
    2020-12-09 09:52

    Here's working example with anonymous output record, if you have any questions place a comment below:                    

    public partial class Form1 : Form
    {
        DataTable table;
        public Form1()
        {
            InitializeComponent();
            #region TestData
            table = new DataTable();
            table.Clear();
            for (int i = 1; i < 12; ++i)
                table.Columns.Add("Col" + i);
            for (int rowIndex = 0; rowIndex < 5; ++rowIndex)
            {
                DataRow row = table.NewRow();
                for (int i = 0; i < table.Columns.Count; ++i)
                    row[i] = String.Format("row:{0},col:{1}", rowIndex, i);
                table.Rows.Add(row);
            }
            #endregion
            bind();
        }
    
        public void bind()
        {
            var filtered = from t in table.AsEnumerable()
                           select new
                           {
                               col1 = t.Field(0),//column of index 0 = "Col1"
                               col2 = t.Field(1),//column of index 1 = "Col2"
                               col3 = t.Field(5),//column of index 5 = "Col6"
                               col4 = t.Field(6),//column of index 6 = "Col7"
                               col5 = t.Field(4),//column of index 4 = "Col3"
                           };
            filteredData.AutoGenerateColumns = true;
            filteredData.DataSource = filtered.ToList();
        }
    }
    

提交回复
热议问题