我想在数据集填充后选择数据集中的特定列(例如列等级)并将值放入列表中
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
}
答案 0 :(得分:4)
您的变量命名让您感到困惑。
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");
答案 1 :(得分:2)
我现在已经解决了我可以改变的问题&#34;等级&#34;我希望列到哪一列,它会显示相关的值。
DataTable scoresTable = ScoresDataSet.Tables[0];
var result = scoresTable.AsEnumerable()
.Select(r => r.Field<string>("Grade")).Where(r => r != null);
var listOfGrades = result.ToList();
答案 2 :(得分:1)
您需要调整此行:
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
答案 3 :(得分:-1)
希望这可以帮到你:
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();
}
}