如何创建dybanic标签并使用asp.net c#通过数据库插入数据 [英] how to create dybanic label and insert data through database using asp.net c#
问题描述
嗨......这是我的代码
hi... here is my code
d=25;
Label[] lb1 = new Label[d];
string strd = "select monthly from feehead where fee_head='" + lb.Text + "'";
da = new SqlDataAdapter(strd, con);
DataSet ds11 = new DataSet();
da.Fill(ds11);
for (int l = 1; l < d; l++)
{
lb1[l].Text = ds11.Tables[0].Rows[0][0].ToString();
}
数据库是:
database is:
CREATE TABLE [FEEHEAD] (
[ACT_CODE] [int] NULL ,
[FEE_HEAD] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[MONTHLY] [bit] NOT NULL ,
[CL_BASED] [bit] NOT NULL ,
[AMOUNT] [float] NULL ,
[SHNAME] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[EMP] [float] NULL ,
[CCL] [float] NULL ,
[SPL] [float] NULL ,
[EXT] [float] NULL ,
[AccG] [int] NULL ,
[HType] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[APR] [bit] NOT NULL ,
[may] [bit] NOT NULL ,
[JUN] [bit] NOT NULL ,
[JUL] [bit] NOT NULL ,
[AUG] [bit] NOT NULL ,
[SEP] [bit] NOT NULL ,
[OCT] [bit] NOT NULL ,
[NOV] [bit] NOT NULL ,
[DECM] [bit] NOT NULL ,
[JAN] [bit] NOT NULL ,
[FEB] [bit] NOT NULL ,
[MAR] [bit] NOT NULL
) ON [PRIMARY]
GO
我的错误是:
对象引用未设置为对象的实例。
and my error is:
Object reference not set to an instance of an object.
推荐答案
Label[] lb1 = new Label[d];
...
for (int l = 1; l < d; l++)
{
lb1[l].Text = ds11.Tables[0].Rows[0][0].ToString();
}
你创建了一个数组,它可以容纳一定数量的标签
对象。创建数组时,所有元素都设置为数组类型的默认值,在本例中为 null
。
然后尝试在数组中的每个元素上设置属性。但是你没有改变任何元素的默认值,所以你试图在 null
引用上设置一个属性。
你需要在循环中创建一个新的 Label
实例,设置它的 Text
属性,然后将其存储在数组中:
You've created an array which can hold a certain number of Label
objects. When you create an array, all of the elements are set to the default value for the array type, which in this case is null
.
You then attempt to set a property on each element in the array. But you haven't changed the default value of any of the elements, so you're trying to set a property on a null
reference.
You need to create a new Label
instance within the loop, set its Text
property, and then store it in the array:
for (int l = 1; l < d; l++)
{
Label label = new Label();
label.Text = ds11.Tables[0].Rows[0][0].ToString();
lb1[l] = label;
}
您可以通过使用调试器逐步执行代码来轻松识别此问题。
You could have easily identified this problem yourself by using the debugger to step through your code.
这篇关于如何创建dybanic标签并使用asp.net c#通过数据库插入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!