如何在运行时创建多个文本框并从数据库中为文本框分配值...我想显示数据库中的所有数据。例如,如果我有4行存储,那么程序应该一次显示动态创建的文本框中的所有4行。 C#窗口表格给我代码或示例谢谢..
int txtno = int.Parse(textBox1.Text);
try
{
string MyConnection2 = "datasource = 127.0.0.1;port=3306;username = root;password =; database = test123; SslMode=None ;Convert Zero Datetime=True";
//Display query
string Query = "select * from test123.task;";
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
// MyConn2.Open();
//For offline connection we weill use MySqlDataAdapter class.
MySqlDataAdapter MyAdapter = new MySqlDataAdapter();
MyAdapter.SelectCommand = MyCommand2;
DataSet ds = new DataSet();
DataTable dTable = new DataTable();
MyAdapter.Fill(dTable);
MyAdapter.Fill(ds);
// MySqlDataReader MyReader2;
foreach (DataRow de in DataSet.TABLe.Row)
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader();
if (MyReader2.Read())
{
string val = MyReader2[0].ToString();
if (val == "")
{
//textBox1.Text = ()
}
else
{
txtno = Convert.ToInt32(MyReader2[0].ToString());
txtno = txtno + 1;
TextBox txt = new TextBox();
// txtno.Text = (i + 1).ToString()
panel2.Controls.Add(txt);
panel2.Show();
textBox1.Text = txtno.ToString();
}
}
//for (int i = 0; i < txtno; i++)
//{
// Label lbl = new Label();
// lbl.Text = (MyReader2["task_comment"].ToString());
// // lbl = "Label" + i.ToString();
// panel2.Controls.Add(lbl);
//}
MyConn2.Close();//Connection closed here
}
catch (Exception ex)
{
}
答案 0 :(得分:0)
有很多更好的方法来编写您想要的内容,但我提供了一种通过指定文本框的Top
和Left
来修复代码的简单方法:
MySqlConnection con = new SqlConnection( "datasource = 127.0.0.1;port=3306;username = root;password =; database = test123; SslMode=None ;Convert Zero Datetime=True");
MySqlCommand cmd = new SqlCommand( "select * from test123.task;", con);
con.open();
MySqlDataReader dr= cmd.ExecuteReader();
int top=100;
While(dr.read())
{
Textbox textBox= new TextBox();
panel2.Controls.Add(textBox);
textBox.Text=dr[0 /* or instead of 0 use your fieldName */].ToString();
textBox.Left=150;
textBox.Top=top;
top+=100;
}
con.close()