繁体   English   中英

在运行时创建多个文本框并从数据库分配值文本框。我想显示数据库中的所有数据

[英]create at run time multiple text box and assign value textbox from database..i want to show all the data from database

我如何在运行时创建多个文本框,并从数据库中为文本框分配值。我想显示数据库中的所有数据。 例如,如果我存储了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)

{

}

有很多更好的编程所需方法的方法,但是我提供了一种简单的方法,通过指定文本框的TopLeft来修复代码:

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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM