select certain columns of a data table
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 |col2 |col3|col4 |col5 |col6|col7 |col8 |col9 |col10 |col11 |
I want to select column col1, col2 col6, col7,col3. and dispay the data in a gridview of the rows within the datatable.. currently the code that i am using is below and onmly selects certain data. I am not selecting the data from sql its data being selected from another excel which is stored in a datatable.. but i am in need of the other columns in another area as well.. this data is being written into a table in word
for (int i = 1; i < table.Rows.Count; i++)
{
for (int j = 0; j < table.Columns.Count; j++)
{
if (j == 0)
{
val = filteredData.Rows[row][col].ToString();
}
else
{
val = filteredData.Rows[row][col].ToString();
if (val == "-" || val == "")
{
val = filteredData.Rows[row][col].ToString();
}
else
{
val = Convert.ToString(Math.Round(Convert.ToDouble(filteredData.Rows[row][col]), MidpointRounding.AwayFromZero));
}
}
table[j, i].TextFrame.Text = val;
col++;
}
First store the table in a view, then select columns from that view into a new table.
System.Data.DataTable table = new System.Data.DataTable();
for (int i = 1; i <= 11; i++)
table.Columns.Add("col" + i.ToString());
for (int i = 0; i < 100; i++)
{
System.Data.DataRow row = table.NewRow();
for (int j = 0; j < 11; j++)
row[j] = i.ToString() + ", " + j.ToString();
table.Rows.Add(row);
}
System.Data.DataView view = new System.Data.DataView(table);
System.Data.DataTable selected = view.ToTable("Selected", false, "col1", "col2", "col6", "col7", "col3");
Used the sample data to test this method I found: Create ADO.NET DataView showing only selected Columns
我们也可以尝试这样,
string[] selectedColumns = new[] { "Column1","Column2"};
DataTable dt= new DataView(fromDataTable).ToTable(false, selectedColumns);
The question I would ask is, why are you including the extra columns in your DataTable if they aren't required?
Maybe you should modify your SQL select statement so that it is looking at the specific criteria you are looking for as you are populating your DataTable.
You could also use LINQ to query your DataTable as Enumerable and create a List Object that represents only certain columns.
Other than that, hide the DataGridView Columns that you don't require.
链接地址: http://www.djcxy.com/p/68830.html上一篇: 修改一个字符串变量
下一篇: 选择数据表的某些列