Asp.net怎样把数据循环添加到数据库 最好有例子

Asp.net怎样把数据循环添加到数据库 最好有例子,第1张

要显示图片的页面设置

<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()

}

如果知道页面TextBox的总数是num的话,就可以这样写:

foreach (Control aa in Page.Controls)

{

if (aa is TextBox)

{

for (int i = 0i <numi++)

{

if (i <num-3)

{

break

}

else

{

TextBox tb = (TextBox)aa

tb.Text = "hello world!"

}

}

}

}


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

原文地址: http://outofmemory.cn/sjk/9892429.html

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

发表评论

登录后才能评论

评论列表(0条)

保存