当前位置: 动力学知识库 > 问答 > 编程问答 >

asp.net - how to bind dataset one column values to textboxes dynamically?

问题描述:

In DataSet I have 4 columns. In button click I have to display the entire one column values in textboxes

dynamically. Like when we see FB comments all comments will be displayed in textboxes dynamically.

please help me.

I am fresher to SW .>

ds = l2.messageshow(); //drag the data into ds

Convert.ToInt32(ds);

int linenum = 0;

foreach (int x in ds)

{

}

when I am using the above code I get the following error:

foreach statement cannot operate on variable of type dataset

网友答案:

Try like the below Code

ds=l2.messageshow();//drag the data into ds
Convert.ToInt32(ds);
int linenum = 0;
foreach (DataRow row in ds.Tables[0].Rows) //Change Here
{   
     //Your code
}

You cant convert the whole DataSet into int to have the line Number use DataRow for getting the data of the DataSet line by line

Edit:

If you want only one column from DataSet to dispaly it in textbox use the below code

if(ds.Tables[0].Rows.Count>0)
  {
    txtBox.Text=ds.Tables[0].Rows[0]["ColumnName"].ToString();
  }

I am assuming your DataSet having only one Table and one Row


If you want to display entire column in textboxes dynamically you may create Textboxes dynamically and assign DataSet Values to it try the below code,

ds=l2.messageshow();//drag the data into ds

int linenum = ds.Tables[0].Rows.Count;

TextBox[] textbox= new TextBox[linenum]; //Modified line

for (int i = 0; i < linenum; i++)
{
  textbox[i] = new TextBox();
  textbox[i].ID = "textbox[" + i + "]";
  PlaceHolder1.Controls.Add(textbox[i]);
  textbox[i].Text=ds.Tables[0].Rows[i]["ColumnName"].ToString();
}

Keep in mind Dynamic Controls will be lost after Postback to retain it follow this Example how-to-retain-values-of-dynamically or This Example Dynamic Controls in Placeholder lossed after postback

网友答案:

As far as I understood your requirements is you want to display entire column rows in textboxes dynamically.

Let's assume that you don't know how many rows your dataset would have. So what you do to create textboxes dynamically equal to the number of your dataset rows?

Let we have a user control containing one TextBox.

Steps To Implement:

  • Count the rows of dataset.
  • Bind the control to a panel or container in a loop having iteration count equal to the dataset rows.
  • In each iteration grab the column value and assign it to the TextBox before docking the control inside the control container.

Code:

 foreach(var row in DataSet.Tables[0].Rows)
 {
  UserControl objCtrl = new UserControl();
  objCtrl.Controls["Your TextBox Id Here"].Text = row["ColumnName"].ToString();
  Panel.Controls.Add(objCtrl);
 }

If Problem Persists in provided solution then please comment.

分享给朋友:
您可能感兴趣的文章:
随机阅读: