How to use executeScalar() inside executeReader()in asp.net using C# - c#

I am getting error :
"There is already an open DataReader associated with this Command
which must be closed first."
Code is as follows :
I am generating dynamic table using 1 table & in every row of that table I want sum calculations from another Table
I have called readDr() first using sqlcommand "cmd" & ExecuteReader(). After that I have called CalTotAmt(string CC) which uses sqlcommand "cmdTotAmt" & ExecuteScalar().
I have used 2 diff sqlcommand still its giving error.
protected void readDr()
{
string str = "select CCNo,TotalAmt,NoOfRect,Energy,New1,Theft,Misc from ChallanTable;";
cmd = new SqlCommand(str, con);
rdr = cmd.ExecuteReader();
}
protected void CreateChallanTable()
{
table.Caption = "Challan Entry";
table.ID = "Challan Entry";
table.BackColor = System.Drawing.Color.Maroon;
table.ForeColor = System.Drawing.Color.Gray;
readDr(); //call to function readDr()
Panel2.Controls.Add(table);
for (i = 0; i < 1; i++)
{
row = new TableRow();
row.BorderStyle = BorderStyle.Ridge;
m = 0;
while (rdr.Read())
{
row = new TableRow();
row.ID = "Row" + m;
row.BorderStyle = BorderStyle.Ridge;
for (n = 0; n <= 6; n++)
{
cell = new TableCell();
cell.ID = "cell" + m + n;
cell.BorderWidth = 5;
cell.BorderStyle = BorderStyle.Ridge;
//cell.BorderColor = System.Drawing.Color.Azure;
for (n = 0; n <= 0; n++)
{
Label lbl = new Label();
lbl.ID = "lblCCRow" + m + n;
lbl.Text = Convert.ToString(rdr[0]);
lbl.Width = 70;
CCNo = lbl.Text;
// Add the control to the TableCell
cell.Controls.Add(lbl);
}
for (n = 1; n <= 1; n++)
{
Label lbl = new Label();
lbl.ID = "lblTotAmt" + m + n;
lbl.Text = Convert.ToString(rdr[1]);
lbl.Width = 70;
TotAmt = Convert.ToDouble(lbl.Text);
// Add the control to the TableCell
cell.Controls.Add(lbl);
Label2.Text = Convert.ToString(CalTotAmt(CCNo));
}
for (n = 2; n <= 2; n++)
{
Label lbl = new Label();
lbl.ID = "lblNoRect" + m + n;
lbl.Text = Convert.ToString(rdr[2]);
lbl.Width = 70;
NoofRects = Convert.ToDouble(lbl.Text);
// Add the control to the TableCell
cell.Controls.Add(lbl);
}
for (n = 2; n <= 2; n++)
{
Label lbl = new Label();
lbl.ID = "lblEnergy" + m + n;
lbl.Text = Convert.ToString(rdr[3]);
lbl.Width =70;
Energy = Convert.ToDouble(lbl.Text);
// Add the control to the TableCell
cell.Controls.Add(lbl);
}
for (n = 3; n <= 3; n++)
{
Label lbl = new Label();
lbl.ID = "lblNew" + m + n;
lbl.Text = Convert.ToString(rdr[4]);
lbl.Width =70;
NewSD = Convert.ToDouble(lbl.Text);
// Add the control to the TableCell
cell.Controls.Add(lbl);
}
for (n = 4; n <= 4; n++)
{
Label lbl = new Label();
lbl.ID = "lblTheft" + m + n;
lbl.Text = Convert.ToString(rdr[5]);
lbl.Width = 70;
Theft = Convert.ToDouble(lbl.Text);
// Add the control to the TableCell
cell.Controls.Add(lbl);
}
for (n = 5; n <= 5; n++)
{
Label lbl = new Label();
lbl.ID = "lblMisc" + m + n;
lbl.Text = Convert.ToString(rdr[6]);
lbl.Width = 70;
Misc = Convert.ToDouble(lbl.Text);
// Add the control to the TableCell
cell.Controls.Add(lbl);
}
row.Cells.Add(cell);
}
// Add the TableRow to the Table
table.Rows.Add(row);
//dr.NextResult();
//outer for-loop end
m++;
}
rdr.Close();
}
protected double CalTotAmt(string CC)
{
double Total = 0;
string str = "select Sum(Amount) from MainDataTable Where CC='" + CC + "' and BU ='" + LogInBU + "'";
SqlCommand cmdTotAmt = new SqlCommand(str,con);
Total = Convert.ToDouble(cmdTotAmt.ExecuteScalar());
Label2.Text = Total.ToString();
return Total;
}
Please help me out.

Here you are trying to open multiple recordset open concurrently on a same connection. You can do that by adding MultipleActiveResultSets=True to the connection string.

Try modifying you code, to make sure DataReader is closed properly:
Sample Code:
protected DataTable readDr()
{
con.Open();
string str = "select CCNo,TotalAmt,NoOfRect,Energy,New1,Theft,Misc from ChallanTable;";
cmd = new SqlCommand(str, con);
rdr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(rdr);
rdr.Close();
con.Close();
}

You would generally fix it by writing a single query that computes all of the results in one go - rather than forcing your code to keep querying the database, over and over.
Something like:
select CCNo,TotalAmt,NoOfRect,Energy,New1,Theft,Misc,SumTotal
from ChallanTable ct
cross apply
(select Sum(Amount) as SumTotal from MainDataTable Where CC=ct.CCNo) t
Then you just have to process the results.
(Also, you have a bug in your display code at present - you have two attempts to do something when n==2, the second for will never be entered)

Related

How can I refer to controls which are created runtime in c#?

I have 2 tables in my database one of which holds things and the other prices. I designed a form which retrieves thing names as checkboxes and adds textboxes against them. They are all created in runtime when the form loads. They all are named in loops accordingly and when form loads I can see them arranged in the way I wanted to. But I cannot refer them in design time in the form as you can see in below where TextBox1.Text is. May you suggest me how I can do this?. Thanks by now. Below is the code I wrote for controls:
public Form4()
{
InitializeComponent();
SqlConnection conn = new SqlConnection("Data Source=ZEFIRAN\\SQLEXPRESS; Initial Catalog=Lab; Integrated Security=true");
conn.Open();
string say = "SELECT COUNT(DISTINCT Thing) FROM Sale";
SqlCommand cmd = new SqlCommand(say, conn);
Int32 ts = Convert.ToInt32(cmd.ExecuteScalar());
conn.Close();
for (int i = 0; i < ts; i++)
{
TextBox tb = new TextBox();
tb.Width = 50;
tb.Height = 25;
tb.Name = "TextBox" + (i + 1).ToString();
tb.Text = i + 1 + ". Test";
panel1.Controls.Add(tb);
int x = 150;
int y = 40;
tb.Location = new System.Drawing.Point(x, 40 + i * y);
}
for (int i = 0; i < ts; i++)
{
TextBox tb = new TextBox();
tb.Width = 50;
tb.Height = 25;
tb.Name = "TextBox" + (2 * i + 1).ToString();
tb.Text = i + 1 + ". Test";
panel1.Controls.Add(tb);
int x = 210;
int y = 40;
tb.Location = new System.Drawing.Point(x, 40 + i * y);
}
List<string> seyler = new List<string>();
conn.Open();
string query = "SELECT Thing FROM Things ORDER BY TNo";
using (SqlCommand cmdtest = new SqlCommand(query, conn))
{
using (SqlDataReader dr = cmdtest.ExecuteReader())
{
while (dr.Read())
{
seyler.Add(dr.GetString(0));
}
}
}
string toplam = "SELECT COUNT(Thing) FROM Things";
SqlCommand tplm = new SqlCommand(toplam, conn);
Int32 top1 = Convert.ToInt32(tplm.ExecuteScalar());
for (int j = 0; j < top1; j++)
{
CheckBox chb = new CheckBox();
panel1.Controls.Add(chb);
int t = 50;
int u = 40;
chb.Location = new System.Drawing.Point(t, 40 + j * u);
chb.Width = 100;
chb.Height = 25;
chb.Text = seyler[j];
chb.Name = "cb" + (j + 1).ToString();
}
conn.Close();
TextBox1.Text = "";
}

Dynamic button not firing click event or page life cycle for button(not dynamic)

I've got different entity types and depending on which entity is clicked (dropdownlist) the amount and types of uploads which is needed is different every time.
Thus, I am creating multiple dynamic upload controls in a dynamic table with a dynamic upload button to upload all files at the same time (I also tried adding a button on the asp.net page as well). Everything creates fine and I can choose the files to upload.
The problem that I am having is that the dynamic button control is not firing its onclicked event, thus I am not able to save the files. I tried creating a button on the asp.net side which does fire, but because of the page life cycle it's not picking up my upload controls.
I then tried to add the OnInit event and created the dynamic button in there and the rest of the upload dynamic controls on the selected index change of the dropdown, but then the everything gets created except the dynamic upload controls. The click event then fires. (the Page_Init does the same).
Preferably I would like the button not to be dynamic but reach the file upload controls to save the files. Is there a way around the page life cycle that I can achieve this or could anybody please tell me what I am doing wrong? Or how can I get the dynamic button to fire the click event?
Any help will be greatly appreciated....
Here is my code of what I done:
protected void lstLegalEntity_SelectedIndexChanged(object sender, EventArgs e)
{
if (CTflag == false)
{
this.Rows = tblRow;
this.Columns = tblCol;
lblAmountOfRows.Text = "4";
CreateDynamicTable();
}
else
{
CTflag = true;
}
clrControls();
}
protected void CreateDynamicTable()
{
string filterstring = "";
filterstring = "SELECT let.ID, UploadType " +
"FROM [dbo].[AssetContract_LegalEntityLinks] lel " +
"INNER Join [dbo].[AssetContract_LegalEntity] le " +
"ON lel.LegalEntityRef = le.ID " +
"INNER JOIN [dbo].[AssetContract_LegalEntityTypes] let " +
"ON lel.LegalTypeRef = let.ID " +
"WHERE lel.LegalEntityRef = #LegalEntityRef ";
cn = new SqlConnection(GetConnectionString());
SqlCommand myCmd = new SqlCommand();
myCmd.CommandText = filterstring;
myCmd.Connection = cn;
myCmd.CommandType = CommandType.Text;
if (lstLegalEntity.SelectedValue != "")
{
myCmd.Parameters.AddWithValue("#LegalEntityRef", Convert.ToInt32(lstLegalEntity.SelectedValue));
}
else
{
myCmd.Parameters.AddWithValue("#LegalEntityRef", Convert.ToInt32(0));
}
cn.Open();
SqlDataReader myReader = myCmd.ExecuteReader();
tblRow = GetUploadControlsCount();
if (CTflag == false)
{
table.Caption = "Upload Requirements";
table.ID = "Upload Requirements";
table.BackColor = System.Drawing.Color.BurlyWood;
divFileUploads.Controls.Add(table);
for (i = 0; i < 1; i++)
{
row = new TableRow();
row.BorderStyle = BorderStyle.Ridge;
for (j = 0; j <= tblCol; j++)
{
cell = new TableCell();
cell.BorderWidth = 5;
cell.BorderStyle = BorderStyle.Ridge;
cell.BorderColor = System.Drawing.Color.Azure;
for (j = 0; j <= tblCol; j++)
{
string[] Header = { "Upload Type", "File" };
Label lbl = new Label();
lbl.ID = "lblHeader" + j;
if (j == 1)
{
lbl.Width = 220;
}
else
{
lbl.Width = 100;
}
lbl.Text = Header[j];
cell.Controls.Add(lbl);
}
row.Cells.Add(cell);
}
table.Rows.Add(row);
}
int readCount = 1;
while (myReader.Read())
{
for (i = 0; i < 1; i++)
{
row = new TableRow();
row.ID = "rw" + myReader["UploadType"].ToString();
row.BorderStyle = BorderStyle.Ridge;
for (j = 0; j <= tblCol; j++)
{
cell = new TableCell();
cell.ID = tbColId + i + j + myReader["UploadType"].ToString(); ;
cell.BorderWidth = 5;
cell.BorderStyle = BorderStyle.Ridge;
cell.BorderColor = System.Drawing.Color.Azure;
for (j = 0; j <= 0; j++)
{
Label lbl = new Label();
lbl.ID = "lblCCRow" + i + "Col" + j + myReader["UploadType"].ToString();
lbl.Text = myReader["UploadType"].ToString();
lbl.Width = 100;
// Add the control to the TableCell
cell.Controls.Add(lbl);
}
for (j = 0; j < 1; j++)
{
fileUp = new FileUpload();
//m = i; n = j;
fileUp.ID = filename + i + readCount.ToString();
fileUp.Width = 350;
cell.Controls.Add(fileUp);
cmdArg = fileUp.ID;
}
row.Cells.Add(cell);
}
table.Rows.Add(row);
readCount++;
}
i = 0;
j = 0;
}
for (i = 0; i < 1; i++)
{
rrow = new TableRow();
rrow.ID = "ResultRow";
rrow.BorderStyle = BorderStyle.Ridge;
rrow.HorizontalAlign = HorizontalAlign.Center;
for (j = 0; j <= tblCol; j++)
{
rcell = new TableCell();
rcell.ID = "resultCol" + j;
rcell.BorderWidth = 5;
rcell.BorderStyle = BorderStyle.Ridge;
rcell.BorderColor = System.Drawing.Color.Azure;
for (j = 0; j < 1; j++)
{
btnUpload = new Button();
btnUpload.Width = 100;
btnUpload.Text = "Upload";
btnUpload.ID = btnUpload.Text;
rcell.Controls.Add(btnUpload);
btnUpload.Click += new EventHandler(UpLdButton_Click);
}
rrow.Cells.Add(rcell);
}
table.Rows.Add(rrow);
}
CTflag = true;
ViewState["dynamictable"] = true;
cn.Close();
myReader.Close();
}
}
protected void UpLdButton_Click(object sender, EventArgs e)
{
for (int i = 0; i < tblRow; i++)
{
fileUp = (FileUpload)FindControlRecursive(this, string.Format("fileUpLoader{0}{1}", 0, i));
//rest of code to save file
}
}
Why don't you use asp repeater to display FileUploads?
you can easily set the html template and design, as DataSource use DataTable of your data
<asp:repeater id='rp' runat='server'>
<ItemTemplate>
<%Eval("UploadType"%> -this is the caption
<asp:fileUpload id='file' runat='server'/>
<asp:Button id='btnUpload' onclick='UploadClick' runat='server'/>
</ItemTemplate>
protected void lstLegalEntity_SelectedIndexChanged(object sender, EventArgs e)
{
//get data into DataTable
rp.DataSource=dt;
rp.DataBnd();
}
protected void UpLdButton_Click(object sender, EventArgs e)
{
for (int i = 0; i < tblRow; i++)
{
//this way you get the relevant fileUpload
fileUp = (FileUpload)((Button)Sender).Parent.FindControl ("file);
//rest of code to save file
}
}
You were on the right track when you added the dynamic buttons in the OnInit event - you just needed to also add the FileUpload controls too.
All of the controls need to be recreated on every postback. .NET automatically handles the controls you added to the ASPX page. You are responsible for the dynamic controls you add programmatically.
Here are a couple of approaches you can take from where you are:
Continue with dynamically adding the control but make the change so you are adding all of the controls, not just the buttons.
If you have a known maximum to the number of controls then you could add then all and control what is displayed using the Visible property. This works when the number of controls is small. It looks like you are putting borders around the table cells so this would not look so good in your case. If you can change the layout so that hiding the controls does not result in residual artifacts then this is an option.

C# Returning a value from a loop at every iteration of the loop?

I'm working on a program right now, and I was wondering if it were possible to have a return function that will return the object/value/variable generated during every loop? Below is the code that I want to work. My only error is the return values.
for (int i = 1; i < ProductArray.Length; i++)
{
Label lbl = new Label();
ThresholdPanel.Controls.Add(lbl);
lbl.Top = A * 28;
lbl.Left = 15;
lbl.Font = new Font(lbl.Font, FontStyle.Bold);
lbl.Text = ProductArray[i];
lbl.Name = "Label" + ProductArray[i];
TextBox txt = new TextBox();
ThresholdPanel.Controls.Add(txt);
txt.Top = A * 28;
txt.Left = 125;
//txt.Text = "Text Box All" + this.A.ToString();
txt.Name = "txt" + A;
textBoxes[txt.Name] = txt;
A = A + 1;
return txt;
return lbl;
}
Thanks in advance and I'm sorry if this is really a simple question....
use yield return instead of return as long as the method returns an IEnumerable<T> where T is the type that you're wanting to yield. It will result in a method that returns a sequence of items, and adds an item to that sequence for every item you yield return.
Use yield return as in provided sample:
IEnumerable<string> Test()
{
for (int i = 1; i < ProductArray.Length; i++)
{
Label lbl = new Label();
ThresholdPanel.Controls.Add(lbl);
lbl.Top = A * 28;
lbl.Left = 15;
lbl.Font = new Font(lbl.Font, FontStyle.Bold);
lbl.Text = ProductArray[i];
lbl.Name = "Label" + ProductArray[i];
TextBox txt = new TextBox();
ThresholdPanel.Controls.Add(txt);
txt.Top = A * 28;
txt.Left = 125;
//txt.Text = "Text Box All" + this.A.ToString();
txt.Name = "txt" + A;
textBoxes[txt.Name] = txt;
A = A + 1;
yield return txt;
}
}
More details on IEnumerable

dynamic object name

To minimize this code using a loop?
DataGridViewComboBoxColumn combo_1 = new DataGridViewComboBoxColumn();
string name_1 = "name_1";
string name1 = "Name 1";
combo_1.Name = name_1;
combo_1.HeaderText = name1;
DataGridViewComboBoxColumn combo_2 = new DataGridViewComboBoxColumn();
string name_2 = "name_2";
string name2 = "Name 2";
combo_2.Name = nazwa_2;
combo_2.HeaderText = nazwa2;
DataGridViewComboBoxColumn combo_3 = new DataGridViewComboBoxColumn();
string name_3 = "name_3";
string name3 = "Name_3";
combo_3.Name = name_3;
combo_3.HeaderText = name3;
DataGridViewComboBoxColumn combo_4 = new DataGridViewComboBoxColumn();
string nazwa_4 = "name_4";
string nazwa4 = "Name 4";
combo_4.Name = name_4;
combo_4.HeaderText = name4;
Sorry for not clear question, I will try to explain...
I want to add table in to datagridview1
// define combobox column
DataGridViewComboBoxColumn combo_1 = new DataGridViewComboBoxColumn();
string name_1 = "name_1";
string name1 = "Name 1";
combo_1.Name = name_1;
combo_1.HeaderText = name1;
// set value to combobox column
pol.Open();
string list_value = "SELECT value FROM table ORDER BY name ASC";
SqlCommand cmd = new SqlCommand(list_value, conn); //conn is defined above in code
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string name = rdr.GetString(0);
combo_1.Items.Add(name); /
}
pol.Close();
// add all column
dataGridView1.Columns.Add("name_column_1", "Name");
dataGridView1.Columns.Add("name_column_2", "Forname");
int index = 2;
dataGridView1.Columns.Insert(index, combo_1);
//add value to cell
DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)dataGridView1.Rows[i].Cells[index];
cell.Value = dt.Rows[i].ItemArray[index];
For "combo_2", "combo_3" etc. I would have to do a few of these fragments differing only in "_1"
If i can use for loop to add combo_1, combo_2, combo_3
//define combobox
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
for (int i = 1; i <= number_column; i++)
{
string name_1 = "name_" + i;
string name1 = "Name " + i;
combo_1.Name = name_1;
combo_1.HeaderText = name1;
}
//add column
for (int i = 1; i <= liczba_kolumn; i++)
{
int nr = 2;
dataGridView1.Columns.Insert(nr, combo);
nr= nr + 1;
}
//set value
for (int i = 0; i < dt.Rows.Count; i++)
{
dataGridView1.Rows.Add();
dataGridView1.Rows[i].Cells[0].Value = dt.Rows[i].ItemArray[0];
dataGridView1.Rows[i].Cells[1].Value = dt.Rows[i].ItemArray[1];
for (int j = 1; j <= number_column; j++)
{
int nr = 2;
DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)dataGridView1.Rows[i].Cells[nr];
cell.Value = dt.Rows[i].ItemArray[nr];
nr = nr + 1;
}
}
error: Additional information: The specified column already belongs to a DataGridView control.
I know why this error is, but i do not know how to change combo name dynamicly.
I'm not sure I understand the question, but I'll take a stab at it...
Let's start with the error you have:
error: Additional information: The specified column already belongs to
a DataGridView control.
I suspect this is because of these 2 lines:
int index = 2;
dataGridView1.Columns.Insert(index, combo);
Do you perhaps mean to use the "i" from your for loop? Or maybe you meant to declare index outside of the for loop (I see you are incrementing it below)?
dataGridView1.Columns.Insert(i, combo);
or
int index = 2;
for (int i = 1; i <= number_of_columns; i++)
{
dataGridView1.Columns.Insert(index, combo);
index = index + 1; // or this could be index++;
}
Now let's look at the title and first line of your question (which is a different topic):
c# dynamic object name
To minimize this code using a loop (or other)?
You could do something like
List<DataGridViewComboBoxColumn> myColumns = new List<DataGridViewComboBoxColumn>();
for(int i=0; i < (the number you want); i++)
{
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
combo.Name = "name_" + i;
combo.HeaderText = "Name " + i;
}
This would give you a (somewhat) dynamic list of DataGridViewComboBoxColumn. However, if you are just going to add them right away, you may prefer:
for(int i=0; i < (the number you want); i++)
{
dataGridView1.Columns.Insert(i, new DataGridViewComboBoxColumn{
Name = "name_" + i,
HeaderText = "Name " + i});
}
I haven't checked that for syntax, but it should at least be close.
Is that what you were going for?
Thanks PhatWrat, you helped me to solve the problem.
pol.Open();
SqlDataAdapter list_adapter = new SqlDataAdapter("SELECT value FROM box ORDER BY value ASC", pol);
DataTable list_dt = new DataTable();
list_adapter.Fill(list_dt);
string[] items = new string[list_dt.Rows.Count];
for (int i = 0; i < list_dt.Rows.Count; i++)
{
items[i] = list_dt.Rows[i][0].ToString();
//MessageBox.Show(list_dt.Rows[i][0].ToString());
}
pol.Close();
int index = 2;
for (int i = 1; i <= number_of_columns; i++)
{
dataGridView1.Columns.Insert(index, new DataGridViewComboBoxColumn
{
Name = "name_" + i,
HeaderText = "Name " + i,
DataSource = items
});
index = index + 1;
}
pol.Open();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM table ORDER BY name ASC", pol);
DataTable dt = new DataTable();
adapter.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
dataGridView1.Rows.Add();
dataGridView1.Rows[i].Cells[0].Value = dt.Rows[i].ItemArray[0];
dataGridView1.Rows[i].Cells[1].Value = dt.Rows[i].ItemArray[1];
int index_2 = 2;
for (int j = 1; j <= number_of_columns; j++)
{
DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)dataGridView1.Rows[i].Cells[index_2];
cell.Value = dt.Rows[i].ItemArray[index_2];
index_2 = index_2 + 1;
}
}
pol.Close();

Increase the label name

I need a command code that increase the label name.
I need to display in 10 (example) labels some texts.
Example:
label1.Text = "1";
label2.Text = "2";
label3.Text = "3";
label4.Text = "4";
label5.Text = "5";
label6.Text = "6";
I need to increase the number from label name (label1, label2, etc.) in a foreach where I will increase the variable i (i will be use in a structure like this label.Name = "label" + i.ToString();).
I hope that you understand what I want to say.
I try this but don't work:
Label[] label = new Label[2];
int ii = 0;
foreach(...) // go through a list
{
label[ii] = new Label();
label[ii].Text = x.materie + tip + "\nsala " + x.sala;
label[ii].Visible = true;
label[ii].Location = new System.Drawing.Point(cX, cY);
label[ii].SetBounds(cX, cY, 98, cH);
label[ii].MinimumSize = new Size(98, cH);
label[ii].MaximumSize = new Size(98, cH);
ii++;
}
int count = 10;
for (int i = 1; i <= count; i++)
{
// setup label and add them to the page hierarchy
Label lbl = new Label();
lbl.Name = "label" + i;
lbl.Text = i.ToString();
//assuming form1 is a form in your page with a runat="server" attribute.
this.Controls.Add(lbl);
}
Assuming you have an array of Label controls, label, you can do the following:
int i = 1;
for (int i = 1; i < label.Length; i++)
{
lbl.ID = String.Format("label{0}", i.ToString());
}

Categories

Resources