【问题标题】:DataSet Select Column数据集选择列
【发布时间】:2015-01-13 20:57:09
【问题描述】:

我想从数据集中选择一个特定的列,一旦它被填充(例如列等级)并将值放入列表中

string excelFile = @"C:\Scores.xlsx";
if (File.Exists(excelFile))
{
    string connString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+excelFile+";Extended Properties=Excel 12.0;";
    var dataAdapter = new OleDbDataAdapter();
    var objConn = new OleDbConnection(connString);

    //SELECT [Name],[Grade],[Location] ect...
    const string query = "SELECT * FROM [TeamScores$]"; 
    var objCmd = new OleDbCommand(query, objConn);

    var table = new DataSet();
    dataAdapter.SelectCommand = objCmd;
    dataAdapter.Fill(table);               

    //I would like to filter the DataSet to select only [Name] and populate the values into a List<string>

    dataGridView1.DataSource = table.Tables[0]; //Will show all results                

}

【问题讨论】:

标签: c# dataset


【解决方案1】:

你的变量命名让你感到困惑。

var table = new DataSet();  // not good at all

DataSet 不是表。 DataSet 包含 DataTables。

试试:

DataSet ScoresDataSet = new DataSet();

然后你可以在桌子上使用 Select 方法(类似...):

DataTable ScoresTable = ScoresDataSet.Tables[0]; 

dataGridView1.DataSource = ScoresTable.Select("Your criteria");

【讨论】:

  • 感谢您抽出宝贵时间帮助我发布了我的做法
【解决方案2】:

希望对您有所帮助:

System.Data.DataSet dsTemp2 = new System.Data.DataSet();


if (dsTemp2.Tables[0].Rows.Count <= 0)
    MessageBox.Show("Records not found");
else
{
    foreach (DataRow dRow in dsTemp2.Tables[0].Rows)
    {
        yourtextbox1.Text = dsTemp2.Tables[0].Rows[0][4].ToString();
        yourtextbox2.Text = dsTemp2.Tables[0].Rows[0][5].ToString();
        yourtextbox3.Text = dsTemp2.Tables[0].Rows[0][7].ToString();
    }
}

【讨论】:

    【解决方案3】:

    我现在已经解决了我可以将“等级”更改为我希望的任何列的问题,它会显示相关的值。

    DataTable scoresTable = ScoresDataSet.Tables[0];                
    var result = scoresTable.AsEnumerable()
        .Select(r => r.Field<string>("Grade")).Where(r => r != null);
    
    var listOfGrades = result.ToList();
    

    【讨论】:

      【解决方案4】:

      你需要调整这条线:

      dataGridView1.DataSource = table.Tables[0]; //Will show all results   
      

      例如这个:

      dataGridView1.DataSource = table.Tables[0].Select("yourField=5")); // you filter the datarows where yourField is 5. 
      

      dataGridView1.DataSource = table.Tables[0].Select("yourField>5 and yourField<21")); // is another example
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-13
        • 2020-07-18
        • 1970-01-01
        • 2021-01-25
        • 2016-07-02
        • 2020-03-20
        相关资源
        最近更新 更多