将数据从Database加载到richtextBox

时间:2013-07-22 20:07:06

标签: c# winforms richtextbox

  using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
            {
                myDatabaseConnection.Open();
                using (SqlCommand mySqlCommand = new SqlCommand("Select [EmpID], [Name], [Address], [Birthday] from EmpTable where EmpID = @EmpID", myDatabaseConnection))
                SqlCommand.Parameters.AddWithValue("@EmpID", textBox1.Text);
                {
                using (SqlDataReader sqlreader = mySqlCommand.ExecuteReader())
                {

                    if (sqlreader.Read())
                    {
                        textBox2.Text = sqlreader.GetInt32(sqlreader.GetOrdinal("EmpID")).ToString();                         
                        textBox3.Text = sqlreader.GetString(sqlreader.GetOrdinal("Name"));
                        textBox4.Text = sqlreader.GetString(sqlreader.GetOrdinal("Address"));
                        textBox5.Text = sqlreader.GetString(sqlreader.GetOrdinal("Birthday"));
                    }
                }
                }
            }

我有这个来显示从数据库到textBox的数据。

enter image description here

如何将数据库中的数据加载到richBox中?像这样的东西:

enter image description here

我可以在哪里突出显示数据并复制文本。

1 个答案:

答案 0 :(得分:2)

使用String.Format,如下所示:

    String template = 
@"EmpID\t\t{0}
Name\t\t{1}
Address\t\t{2}
Birthday\t\t{3}";

    using (SqlConnection c = new SqlConnection( config.ConnectionString ))
    {
        c.Open();
        using (SqlCommand cmd = new SqlCommand("Select [EmpID], [Name], [Address], [Birthday] from EmpTable where EmpID = @EmpID", c))
        {
            cmd.Parameters.AddWithValue("@EmpID", textBox1.Text);
            using (SqlDataReader rdr = mySqlCommand.ExecuteReader())
            {
                if (rdr.Read())
                {
                    Int32  empId = rdr.GetInt32(rdr.GetOrdinal("EmpID")).ToString();                         
                    String name  = sqlreader.GetString(sqlreader.GetOrdinal("Name"));
                    String addr  = sqlreader.GetString(sqlreader.GetOrdinal("Address"));
                    String bday  = sqlreader.GetString(sqlreader.GetOrdinal("Birthday"));

                    textbox.Text = String.Format(template, empId, name, addr, bday);
                }//if
            }//using
        }//using