简体   繁体   English

C# Windows 窗体应用程序 - 在文本框中显示 sql server 值

[英]C# Windows Forms Application - display sql server values in textbox

I need assistance to display sql server values in a windows forms.我需要帮助才能在 Windows 窗体中显示 sql server 值。 In the application below if the query returns a row then the values are displayed.在下面的应用程序中,如果查询返回一行,则显示值。 I understand that I am to use sqldatareader but so far I have been unsuccessful how to add it.我知道我要使用 sqldatareader 但到目前为止我一直没有成功添加它。

SqlConnection ChuoDB_Connection = new SqlConnection("Data Source=test-PC\\tester;Initial Catalog=Chuo;Integrated Security=True;Pooling=False");

    SqlDataAdapter select_adapt;

private void btn_guardian_student_search_Click(object sender, EventArgs e)
    {
        if (rd_btn_guardian_student_no.Checked == true)

        {
            DataSet ds = new DataSet();
            SqlDataReader dr;
            ChuoDB_Connection.Open();
select_adapt = new SqlDataAdapter("SELECT * FROM Guardian WHERE STUDENT_NO = @student_no", ChuoDB_Connection);

select_adapt.SelectCommand.Parameters.Add("@student_no", SqlDbType.Int).Value = Convert.ToInt32(txt_bx_guardian_student_search.Text);

            select_adapt.Fill(ds);

            if (ds.Tables[0].Rows.Count == 0)
            {
                lbl_guardian_student_search.Text = "No Guardian record exists for this student. Please enter the Guardian Information";
                ChuoDB_Connection.Close();

            }

            if (ds.Tables[0].Rows.Count > 0)
            {
                lbl_guardian_student_search.Text = "";       

              while (dr.read())
                {
                    txtBox1.Text = rdr.Item["DBFieldName1"].ToString();
                    txtBox2.Text = rdr.Item["DBFieldName2"].ToString();
                }



            }                


        }
    }

I think you do not need DataAdapter and DataSet here.我认为您在这里不需要 DataAdapter 和 DataSet 。 Try just with the DataReader:尝试使用 DataReader:

string _connectionString = "Data Source=test-PC\\tester;Initial Catalog=Chuo;Integrated Security=True;Pooling=False";

string _selectCommand = @"SELECT * FROM Guardian WHERE STUDENT_NO = @student_no";

here code for the click handler:点击处理程序的代码如下:

 SqlParameter parameter = new SqlParameter("@student_no", SqlDbType.Int);
 parameter.Value = Convert.ToInt32(txt_bx_guardian_student_search.Text);

    using (IDbConnection connection = new SqlConnection(_connectionString))
            {
                connection.Open();

                using (IDbCommand command = connection.CreateCommand())
                {
                    command.Connection = connection;
                    command.CommandText = _selectCommand;
                    command.Parameters.Add("@student_no", SqlDbType.Int).Value = Convert.ToInt32(txt_bx_guardian_student_search.Text);

                    IDataReader reader = command.ExecuteReader();


                    if (reader.Read())
                    {
                        txtBox1.Text = reader["DBFieldName1"].ToString();
                        txtBox2.Text = reader["DBFieldName2"].ToString();
                    }
                    else
                    {
                        lbl_guardian_student_search.Text = "No Guardian record exists for this student. Please enter the Guardian Information";
                    }
                }
            }

To use a SqlDataReader you need to initialize it using the ExecuteReader method of a SqlCommand.要使用 SqlDataReader,您需要使用 SqlCommand 的 ExecuteReader 方法对其进行初始化。 So in your code you could discard all the part relative to the SqlDataAdapter因此,在您的代码中,您可以丢弃与 SqlDataAdapter 相关的所有部分

private void btn_guardian_student_search_Click(object sender, EventArgs e)
{
    if (rd_btn_guardian_student_no.Checked == true)
    {
        using(SqlConnection cnn = new SqlConnection(......))
        using(SqlCommand cmd = new SqlCommand(@"SELECT * FROM Guardian 
                                   WHERE STUDENT_NO = @student_no", cnn))
        {
           cnn.Open();
           cnn.Add("@student_no", SqlDbType.Int).Value = Convert.ToInt32(txt_bx_guardian_student_search.Text);
           using(SqlDataReader rd = new cmd.ExecuteReader())
           {
               if(!rd.HasRows)
                  lbl_guardian_student_search.Text = "No Guardian record exists for this student. Please enter the Guardian Information";
               else
               {
                  rdr.Read();
                  txtBox1.Text = rdr.Item["DBFieldName1"].ToString();
                  txtBox2.Text = rdr.Item["DBFieldName2"].ToString();
               }
           }                
       }
   }
}

Note that I have moved the global connection object inside the code making it a local variable that is initialized inside a using block as well the command and the reader.请注意,我已将全局连接对象移动到代码中,使其成为在 using 块以及命令和读取器中初始化的局部变量。 They are disposable objects and should be disposed when you have finished with them.它们是一次性物品,用完后应丢弃。 The Using Statement ensure correct dispose of these objects Using 语句确保正确处理这些对象

Also note that keeping a connection opened all the time of your application is really a big NO-NO in database server applications.另请注意,在应用程序的所有时间保持连接打开在数据库服务器应用程序中确实是一个很大的禁忌。 You hinder the server ability to serve more requests if you keep your connection constantly open.如果您保持连接不断打开,您会阻碍服务器为更多请求提供服务的能力。 And there is no great penalty in restoring the server connection because ADO.NET has an infrastructure called Connection Pooling that allows you to restore your connection immediately恢复服务器连接不会有太大的损失,因为 ADO.NET 有一个称为连接池的基础结构,它允许您立即恢复连接

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

相关问题 针对SQL DB的C#Windows窗体应用程序文本框验证 - C# Windows Forms Application textbox validation against SQL DB 无法将值动态创建的文本框插入或更新到SQL Server数据库Windows Forms C#中 - Can't Insert or update values to dynamically created textbox into SQL Server database Windows Forms C# 服务器 - C# Windows Forms and SQL Server C#Windows窗体应用程序逐行读取文本框 - C# Windows Forms Application Read Textbox Line by Line 打开/保存多个文本框值C#Windows窗体 - Open/save multiple textbox values c# windows forms 在 C# 列表框或文本框中显示来自 SQL 服务器数据库表的日期列值 - Display Date Column values from a SQL Server database table in a C# listbox or textbox 使用Windows窗体和C#将Excel文件保存在应用程序文件夹中并将内容上传到SQL Server - Saving excel file in application folder and uploading the content to SQL Server using windows forms and C# 使用SMO备份带有C#Windows Forms应用程序的SQL Server 2005数据库时,备份失败 - Using SMO to backup SQL Server 2005 Database with C# Windows Forms Application, Back up failed C# Windows Forms 应用程序不显示localDB数据 - C# Windows Forms application does not display localDB data C#Windows表单文本框显示为灰色 - C# Windows forms textbox greyed out
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM