採取於msdn文章在DataBind
屬性。
ASP實例
void Page_Load(Object sender, EventArgs e)
{
// This example uses Microsoft SQL Server and connects
// to the Northwind sample database. The data source needs
// to be bound to the GridView control only when the
// page is first loaded. Thereafter, the values are
// stored in view state.
if(!IsPostBack)
{
// Declare the query string.
String queryString =
"Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]";
// Run the query and bind the resulting DataSet
// to the GridView control.
DataSet ds = GetData(queryString);
if (ds.Tables.Count > 0)
{
AuthorsGridView.DataSource = ds;
AuthorsGridView.DataBind();
}
else
{
Message.Text = "Unable to connect to the database.";
}
}
}
DataSet GetData(String queryString)
{
// Retrieve the connection string stored in the Web.config file.
String connectionString = ConfigurationManager.ConnectionStrings["NorthWindConnectionString"].ConnectionString;
DataSet ds = new DataSet();
try
{
// Connect to the database and run the query.
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);
// Fill the DataSet.
adapter.Fill(ds);
}
catch(Exception ex)
{
// The connection failed. Display an error message.
Message.Text = "Unable to connect to the database.";
}
return ds;
}
此片段顯示瞭如何(一)數據集綁定到GridView,通過使用數據綁定方法分配它。
該網站還表示:
使用的DataBind()方法來從數據源到GridView控制數據綁定。此方法解析了控件的活動模板中的所有數據綁定表達式。
SOLUTION
我想引用線話說:
AuthorsGridView.DataBind();
這實際上結合數據到控制。
邊注
爲了保護自己免受SQLI,你應該SQL Parameters讀了起來,而不是直接串聯。
WINFORM例
教程發現:here
//create the connection string
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\myDatabase.mdb";
//create the database query
string query = "SELECT * FROM MyTable";
//create an OleDbDataAdapter to execute the query
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, connString);
//create a command builder
OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(dAdapter);
//create a DataTable to hold the query results
DataTable dTable = new DataTable();
//fill the DataTable
dAdapter.Fill(dTable);
另外:
//the DataGridView
DataGridView dgView = new DataGridView();
//BindingSource to sync DataTable and DataGridView
BindingSource bSource = new BindingSource();
//set the BindingSource DataSource
bSource.DataSource = dTable;
//set the DataGridView DataSource
dgView.DataSource = bSource;
刪除此行dataGridView1.DataSource =「」; ,包括更多的細節,以便我們可以幫助您... – 2014-10-07 12:35:05
我的登錄名是...'MrSQLInjection'); DROP TABLE LibraryInfo; - 'P.s.請不要使用我的名字;) – Reniuz 2014-10-07 12:37:22
OP缺少的唯一部分是'dataGridView1.DataBind();' – 2014-10-07 12:39:03