以下是ASP.NET基本控件的数据绑定:
webconfig:
<appSettings>
<add key="ConnectionString" value="server=.;database=shujuku;uid=sa;pwd=123" />
</appSettings>
1.gridview:
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"].ToString());
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from 表", conn);
DataSet ds = new DataSet();
try
{
da.Fill(ds, "testTable");
this.GridView1.DataSource = ds.Tables["testTable"];
this.GridView1.DataBind();
}
catch (Exception error)
{
Response.Write(error.ToString());
}
finally
{
conn.Close();
}
2.DataList:
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"].ToString());
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from 表", conn);
DataSet ds = new DataSet();
try
{
da.Fill(ds, "testTable");
this.DataList1.DataSource = ds.Tables["testTable"];
this.DataList1.DataBind();
}
catch (Exception error)
{
Response.Write(error.ToString());
}
finally
{
conn.Close();
}
3.SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"].ToString());
conn.Open();
try
{
SqlDataAdapter da = new SqlDataAdapter("select * from 表", conn);
DataSet ds = new DataSet();
da.Fill(ds, "testTable");
this.DropDownList1.DataTextField = "字段";
this.DropDownList1.DataValueField = "id";
this.DropDownList1.DataSource = ds.Tables["testTable"];
this.DropDownList1.DataBind();
}
catch (Exception error)
{
Response.Write(error.ToString());
}
finally
{
conn.Close();
}
4.ListBox:
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"].ToString());
try
{
SqlDataAdapter da = new SqlDataAdapter("select id from table", conn);
DataSet ds = new DataSet();
da.Fill(ds, "testTable");
this.ListBox1.DataTextField = "id";
this.ListBox1.DataValueField = "id";
this.ListBox1.DataSource = ds.Tables["testTable"];
this.ListBox1.DataBind();
}
catch (Exception error)
{
Response.Write(error.ToString());
}
finally
{
conn.Close();
}
5.Lable
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"].ToString());
SqlDataAdapter da = new SqlDataAdapter("select id from table", conn);
DataSet ds = new DataSet();
try
{
da.Fill(ds, "testTable");
this.Lable1.Text=ds.Tables[0].Rows[0]["id"].Tostring();
}
catch (Exception error)
{
Response.Write(error.ToString());
}
finally
{
conn.Close();
}