Insus.NET有很久以前,有帮网友写过一个小例子《输入数字动态创建行》http://www.cnblogs.com/insus/archive/2011/12/01/2270455.html 不过只是实现了前面一部分,没有获取与存储入数据库功能均没有实现。
近来几天,连接到几个网友的要求,需把它做成一个完整的例子。实现之前,先对原程序修改2处地方:
把TextBox 的ID由TextBox1改为TextBoxNum。如果不改,它会影响动态产的TextBox。
另外一个:
把原来click的事件代码,写成一个私有方法,然后分别在page_load和click事件中应用。
然后你需要在数据库创建表,创建自定义类别,创建存储过程:
上面SQL语句可从下面拷贝:
CREATE TABLE [dbo].[TData] ( [TData_nbr] INT IDENTITY(1,1) PRIMARY KEY NOT NULL, [ImgSource] NVARCHAR(30) NULL, [Title] NVARCHAR(50) NULL, [Description] NVARCHAR(100) NULL, [Album] NVARCHAR(20) NULL ) GO CREATE TYPE [dbo].[udt_TData] AS TABLE( [ImgSource] NVARCHAR(30) NULL, [Title] NVARCHAR(50) NULL, [Description] NVARCHAR(100) NULL, [Album] NVARCHAR(20) NULL ) GO CREATE PROCEDURE [dbo].[usp_TData_Insert] ( @TData [dbo].[udt_TData] READONLY ) AS INSERT INTO [dbo].[TData] ([ImgSource],[Title],[Description],[Album]) SELECT [ImgSource],[Title],[Description],[Album] FROM @TData GO
接下来,你可以在程序中,创建一个类别:
现在你可以写“上传图片”铵钮的事件了:
上面截图可复制代码:
DataTable td = new DataTable(); td.Columns.Add("ImgSource", typeof(string)); td.Columns.Add("Title", typeof(string)); td.Columns.Add("Description", typeof(string)); td.Columns.Add("Album", typeof(string)); int rowIndex = 0; for (int idx = 0; idx < TableUploadlayout.Rows.Count; idx++) // (TableRow tr in TableUploadlayout.Rows) { if (idx != rowIndex) //略过表格头行。 { string imgSource = string.Empty; string title = string.Empty; string desc = string.Empty; string album = string.Empty; foreach (TableCell tc in TableUploadlayout.Rows[idx].Cells) { foreach (Control ctl in tc.Controls) { if (ctl is FileUpload) { FileUpload fud = (FileUpload)ctl; string uploadfile = fud.PostedFile.FileName; //处理图片存储... imgSource = uploadfile.Substring(uploadfile.LastIndexOf(@"") + 1); } if (ctl is TextBox) { TextBox tb = (TextBox)ctl; int id = Convert.ToInt32(tb.ID.Substring(7)); if (id % 2 == 1) //第一个文本框 title = tb.Text; if (id % 2 == 0) //第二个文本框 desc = tb.Text; } if (ctl is DropDownList) { DropDownList ddl = (DropDownList)ctl; album = ddl.SelectedValue; } } } td.Rows.Add(imgSource, title, desc, album); } } TData tData = new TData(); tData.TD = td; tData.AddRecord();
最后做一个动画演示: