如何在文本框中显示数据库数据? [英] How do I display a database data into my textbox?

查看:458
本文介绍了如何在文本框中显示数据库数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这里有这个程序代码,我在整个表格中使用:



I have this program code here that I use throughout my forms:

void totalqty()
        {
            string constring = "Data Source=D-HOS-MIS2;Initial Catalog=Consignment_db;Persist Security Info=True;User ID=sa;Password=t.july.01";
            string query = "select sum(SRT_Qty) as SRT_Total from StockReqTemp";
            SqlConnection con_db = new SqlConnection(constring);
            SqlCommand cmd = new SqlCommand(query, con_db);
            SqlDataReader reader;

            try
            {
                con_db.Open();
                reader = cmd.ExecuteReader();
                while(reader.Read())
                {
                    
                }
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }





我的尝试:



我试过:





What I have tried:

I have tried:

SR_TotalQty.Text = (dr["SRT_Total"].ToString());





但它不起作用。我知道如何通过listview和组合框显示来自数据库的数据,但不知道如何在文本框中显示数据。



but it doesn't work. I know how to show data from database through listview and and combobox but not in a textbox.

推荐答案

由于您只使用单个聚合值,我会使用ExecuteScalar:

Since you are only working with a single aggregate value, I'd use ExecuteScalar:
string constring = "Data Source=D-HOS-MIS2;Initial Catalog=Consignment_db;Persist Security Info=True;User ID=sa;Password=t.july.01";
string query = "select sum(SRT_Qty) as SRT_Total from StockReqTemp";
using (SqlConnection con_db = new SqlConnection(constring))
    {
    using (SqlCommand cmd = new SqlCommand(query, con_db))
        {
        try
            {
            con_db.Open();
            SR_TotalQty.Text = cmd.ExecuteScalar().ToString();
            }
        catch (Exception ex)
            {
            MessageBox.Show(ex.Message);
            }
        }
    }


这篇关于如何在文本框中显示数据库数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆