怎样用Asp.NET读数据循环添加到页面中?

怎样用Asp.NET读数据循环添加到页面中?,第1张

根本不用写循环的啊,你可以使用数据绑定控件,例如GridView,Repeater,DataList,使用这三个控件中的任何一个都可以啊,并为控件绑定一个数据源控件,例如SqlDataSource或者ObjectDataSource,数据源控件从并伍段数据库中取出新闻表的标题和ID。

然后使用数据绝誉绑定控件的项模板,在项模板中添加一个HyperLink控件,用HyperLink的Text属性绑定新闻的标题,NavigateUrl一个地址字符串,例如NavigateUrl='<%#Eval("ID","NewsDetails.aspx?id={0}"橘冲)%>'

要显示图片的页面设置

<asp:datalist id="MyList" repeatcolumns="2" borderwidth="0" runat="server"做扰敏>

<ItemTemplate>

<table>纯枝

<tr>

<td>

<img width=40 height=40 src='<%# DataBinder.Eval(Container.DataItem, "ImgId", "Img.aspx?id=")%>'>

</td>

</tr>

</table>

</ItemTemplate>

</asp:datalist>

后台代码

OleDbConnection objConn = new OleDbConnection()

objConn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0Data Source=" + Server.MapPath("Data.mdb")

objConn.Open()

OleDbCommand objCmd = new OleDbCommand("select * from tbl_Image", objConn)

OleDbDataAdapter da = new OleDbDataAdapter(objCmd)

DataSet ds = new DataSet()

da.Fill(ds, "aa")

MyList.DataSource = ds.Tables["aa"]

MyList.DataBind()

objConn.Close()

img.aspx页面代码

int id = int.Parse(Request["id"].ToString())

OleDbConnection objConn = new OleDbConnection()

objConn.ConnectionString = @"李山Provider=Microsoft.Jet.OLEDB.4.0Data Source=" + Server.MapPath("Data.mdb")

objConn.Open()

OleDbCommand objCmd = new OleDbCommand("select top 1 Image from tbl_Image where ImgId=@id order by ImgId desc",objConn)

objCmd.Parameters.Add("@id", OleDbType.Integer)

objCmd.Parameters["@id"].Value = id

OleDbDataReader objDr = objCmd.ExecuteReader()

while(objDr.Read())

{

Response.BinaryWrite((byte[])objDr["Image"])

}

objDr.Close()

objConn.Close()

把所有得记录存入一个集合,在用事务一次性存入数据库 参考代码如下(凳配卜仅供参考):

SqlConnection myConnection = new SqlConnection("Data Source=localhostInitial Catalog=NorthwindIntegrated Security=SSPI")

myConnection.Open()

SqlTransaction myTrans = myConnection.BeginTransaction()//使用New新生成一个事务

SqlCommand myCommand = new SqlCommand()

myCommand.Transaction = myTrans

try

{

for(....)//枣穗这儿卖冲做循环插入

{

myCommand.CommandText = "Update Address set location='23 rain street' where userid='0001'"

myCommand.ExecuteNonQuery()

}

myTrans.Commit()

}

catch(Exception e)

{

myTrans.Rollback()

}

finally

{

myConnection.Close()

}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/bake/11993011.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-20
下一篇2023-05-20

发表评论

登录后才能评论

评论列表(0条)

    保存