DataGridView 中怎么读取SQLserver数据库的数据,进行显行.

ESEVV 2007-03-09 12:47:56
DataGridView 中怎么读取SQLserver数据库的数据,进行显行
好心人贴下代码哦! 谢谢了.
...全文
529 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
ESEVV 2007-03-09
  • 打赏
  • 举报
回复
谢谢楼上哦!
小妹感激不尽呀...
北京的雾霾天 2007-03-09
  • 打赏
  • 举报
回复
不是DataGridView 中读取数据显示,而是选读出数据用DataGridView来显示.

参考下如下的MSDN示例:
下面的代码示例演示如何初始化简单数据绑定 DataGridView。它还演示如何设置 DataSource 属性。若要运行此示例,请执行以下操作:将以下代码粘贴到一个窗体中,该窗体包含名为 dataGridView1 的 DataGridView;将代码中指定的 connectionString 变量的值替换为对运行该示例的系统有效的字符串;在窗体的构造函数或 Load 事件处理程序中调用 InitializeDataGridView 方法。

C# 复制代码
private void InitializeDataGridView()
{
try
{
// Set up the DataGridView.
dataGridView1.Dock = DockStyle.Fill;

// Automatically generate the DataGridView columns.
dataGridView1.AutoGenerateColumns = true;

// Set up the data source.
bindingSource1.DataSource = GetData("Select * From Products");
dataGridView1.DataSource = bindingSource1;

// Automatically resize the visible rows.
dataGridView1.AutoSizeRowsMode =
DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders;

// Set the DataGridView control's border.
dataGridView1.BorderStyle = BorderStyle.Fixed3D;

// Put the cells in edit mode when user enters them.
dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter;
}
catch (SqlException)
{
MessageBox.Show("To run this sample replace connection.ConnectionString" +
" with a valid connection string to a Northwind" +
" database accessible to your system.", "ERROR",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
System.Threading.Thread.CurrentThread.Abort();
}
}

private static DataTable GetData(string sqlCommand)
{
string connectionString = "Integrated Security=SSPI;" +
"Persist Security Info=False;" +
"Initial Catalog=Northwind;Data Source=localhost";

SqlConnection northwindConnection = new SqlConnection(connectionString);

SqlCommand command = new SqlCommand(sqlCommand, northwindConnection);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = command;

DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
adapter.Fill(table);

return table;
}


ESEVV 2007-03-09
  • 打赏
  • 举报
回复
呀,这里不是女同志多的是?
北京的雾霾天 2007-03-09
  • 打赏
  • 举报
回复
小妹感激不尽呀...
-------------------------------
楼主是女同志???

难得啊!
baseyueliang 2007-03-09
  • 打赏
  • 举报
回复
dataGridView1.DataSource = GetData("Select * From Products");
//关键是这句, dataGridView1把一个TableTable作为显示用的数据源

110,535

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧