C# 将 SqlDataSource 转换为 DataTable 和 DataView
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9452763/
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
Convert SqlDataSource to DataTable and DataView
提问by Ali Ahmed
I have the following SqlDataSourceand I want to convert it to DataViewand read a column from it:
我有以下内容SqlDataSource,我想将其转换为DataView并从中读取一列:
SELECT
dbo.Divisions.DivisionShortcut,
COUNT(DISTINCT dbo.UserQuiz.Username) AS [Number of Participants]
FROM
dbo.Divisions
INNER JOIN
dbo.employee ON dbo.Divisions.SapCode = dbo.employee.DivisionCode
INNER JOIN
dbo.UserQuiz ON dbo.employee.Username = dbo.UserQuiz.Username
INNER JOIN
dbo.Quiz ON dbo.UserQuiz.QuizID = dbo.Quiz.QuizID
WHERE
(dbo.Quiz.QuizID = @QuizID)
GROUP BY
dbo.Divisions.DivisionShortcut
This SqlDataSourcelets the user enter the number of the Quiz, and it will retrieve the total number of participants in that quiz. I want to convert this SqlDataSourceto a DataTableand read a column from it.
这SqlDataSource让用户可以输入测验的数量,它会检索该测验的参与者总数。我想将其转换SqlDataSource为 aDataTable并从中读取一列。
So how to do that?
那么怎么做呢?
回答by marc_s
The SqlDataSource has a Select method which you can call to get back a DataView from your SqlDataSource - see the MSDN documentation on that.
SqlDataSource 有一个 Select 方法,您可以调用该方法从您的 SqlDataSource 取回 DataView - 请参阅有关该的MSDN 文档。
SqlDataSource dataSource = new SqlDataSource(connectionString, selectSql);
DataView view = (DataView)dataSource.Select(args);
DataTable table = view.ToTable();
Is that what you're looking for??
这就是你要找的??
回答by Sami
Let me say you have an SqlDataSourcenamed as SqlDataSource1
让我说你有一个SqlDataSource名为 SqlDataSource1
DataSourceSelectArguments args = new DataSourceSelectArguments();
DataView view = (DataView)SqlDataSource1.Select(args);
DataTable dt = view.ToTable();
Now you can read a column easily from this dt(DataTable) e.g.
现在您可以轻松地从此 dt(DataTable) 读取一列,例如
int columnNumber = 0;
for(int i=0;i<dt.Rows.Count;i++)
{
MessageBox.Show(dt.Rows[i][columnNumber].ToString());
}

