asp.net基本控件的数据绑定的方法

时间:2021-04-16

  以下是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();
}

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章