我是照着一本书上,做一个图书管理系统,其中的会员管理模块里面,和书中打的一模一样,可就是在我这里不能显示出数据库里的东西。我找了很久都没看出问题在哪,请高手帮帮我吧。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
namespace BookStore
{
    public partial class CustomerForm : Form
    {
        protected SqlConnection conn;
        protected SqlCommand cmd;
                public CustomerForm()
        {
            InitializeComponent();
        }
        private void CustomerForm_Load(object sender, EventArgs e)
        {
            try
            {
                conn = new SqlConnection
                (ConfigurationManager.ConnectionStrings["BookStore.Properties.Settings.BookStoreConnectionString"].ConnectionString);
                cmd = new SqlCommand();
                cmd.Connection = conn;
               conn.Open();
                this.InitData();
            }
            catch (Exception exp)
            {
                MessageBox.Show("无法建立数据连接:" + exp.Message);
                this.Close();
            }
        }
           
            private void CustomerForm_FormClosing(object sender, FormClosingEventArgs e)
            {
                if (conn != null && conn.State != ConnectionState.Closed)
                    conn.Close();
            }
        protected void InitData()
        {
            cmd.CommandText = "select distinct [ID] from [Customer] order by [ID]";
            SqlDataReader reader1 = cmd.ExecuteReader();
            cmbCustomerID.Items.Clear();
            while (reader1.Read())
                cmbCustomerID.Items.Add(reader1[0]);
            reader1.Close();
            
        }        private void btnQuery_Click(object sender, EventArgs e)
        {
            if (cmbCustomerID.Text == "")
                return;
          
            cmd.CommandText = "select * from [Customer] where ID=" + cmbCustomerID.Text;
            SqlDataReader reader1 = null;
            try
            {
                reader1 = cmd.ExecuteReader();
                if (reader1.Read())
                {
                    tbName.Text = reader1["Name"].ToString();
                    nudLevels.Value = (short)reader1["Levels"];
                    if ((bool)reader1["Gender"])
                        rbMan.Checked = true;
                    else
                        rbWoman.Checked = true;
                    dtpBirthday.Value = (DateTime)reader1["Birthday"];
                    cmbDegree.Text = reader1["Degree"].ToString();
                    tbAddress.Text = reader1["Address"].ToString();
                    tbTelephone.Text = reader1["Telephone"].ToString();
                    tbEmail.Text = reader1["Email"].ToString();
                    nudScore.Value = (int)reader1["Score"];                }
                else
                {
                    MessageBox.Show("没有符合条件的记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
            }
            catch (Exception exp)
            {
                MessageBox.Show("数据访问错误:" + exp.Message + exp.StackTrace, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (reader1 != null && !reader1.IsClosed)
                    reader1.Close();
            }
        }        private void btnSave_Click(object sender, EventArgs e)
        {
            if (cmbCustomerID.Text == "")
                return;
            if (tbName.Text == "")
            {
                MessageBox.Show("姓名不能为空", "提示",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                tbName.Focus();
                return;
            }
            if (MessageBox.Show("确认保存所进行的修改吗?", "提示",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                return;
            StringBuilder sb1 = new StringBuilder("update [Customer] set name='");
            sb1.Append(tbName.Text);
            sb1.Append("', Levels=");
            sb1.Append(nudLevels.Value);
            sb1.Append(", Gender=");
            if (rbMan.Checked)
                sb1.Append("1");
            else
                sb1.Append("0");
            sb1.Append(", Birthday='");
            sb1.Append(dtpBirthday.Value.ToShortDateString());
            sb1.Append("', Degree='");
            sb1.Append(cmbDegree.Text);
            sb1.Append("', Address='");
            sb1.Append(tbAddress.Text);
            sb1.Append("', Telephone='");
            sb1.Append(tbTelephone.Text);
            sb1.Append("', Email='");
            sb1.Append(tbEmail.Text);
            sb1.Append("', Score=");
            sb1.Append(nudScore.Value);
            sb1.Append(" where ID=");
            sb1.Append(cmbCustomerID.Text);
            cmd.CommandText=sb1.ToString();            try
            {
                if (cmd.ExecuteNonQuery() > 0)
                    MessageBox.Show("保存成功!", "提示", MessageBoxButtons.OK,
                        MessageBoxIcon.Information);
                else
                    MessageBox.Show("未修改任何记录", "提示", MessageBoxButtons.OK,
                        MessageBoxIcon.Asterisk);
            }
            catch (Exception exp)
            {
                MessageBox.Show("数据访问错误:" + exp.Message);
            }
        }       
    }
}

解决方案 »

  1.   

    protected void InitData() 
            { 
                cmd.CommandText = "select distinct [ID] from [Customer] order by [ID]"; 
                SqlDataReader reader1 = cmd.ExecuteReader(); 
                cmbCustomerID.Items.Clear(); 
                while (reader1.Read()) 
                    cmbCustomerID.Items.Add(reader1[0]); 
                reader1.Close(); 
                
            } 你调试一下看看这个reader1里面有没有数据的
      

  2.   

    SqlCommand 是一个短暂对象 通常用了就关了。要用时再new就可以了
      

  3.   

    而我往cmbCustomerID控件中输入1来查询时,就会报个错:
                   
    未处理 System.NullReferenceException
      Message="未将对象引用设置到对象的实例。"
      Source="BookStore"
      StackTrace:
           在 BookStore.CustomerForm.btnQuery_Click(Object sender, EventArgs e) 位置 D:\Backup\我的文档\Visual Studio 2005\Projects\BookStore\BookStore\CustomerForm.cs:行号 67
           在 System.Windows.Forms.Control.OnClick(EventArgs e)
           在 System.Windows.Forms.Button.OnClick(EventArgs e)
           在 System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
           在 System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
           在 System.Windows.Forms.Control.WndProc(Message& m)
           在 System.Windows.Forms.ButtonBase.WndProc(Message& m)
           在 System.Windows.Forms.Button.WndProc(Message& m)
           在 System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
           在 System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
           在 System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
           在 System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
           在 System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
           在 System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
           在 System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
           在 System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
           在 System.Windows.Forms.Form.ShowDialog()
           在 BookStore.Form1.button3_Click(Object sender, EventArgs e) 位置 D:\Backup\我的文档\Visual Studio 2005\Projects\BookStore\BookStore\Form1.cs:行号 27
           在 System.Windows.Forms.Control.OnClick(EventArgs e)
           在 System.Windows.Forms.Button.OnClick(EventArgs e)
           在 System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
           在 System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
           在 System.Windows.Forms.Control.WndProc(Message& m)
           在 System.Windows.Forms.ButtonBase.WndProc(Message& m)
           在 System.Windows.Forms.Button.WndProc(Message& m)
           在 System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
           在 System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
           在 System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
           在 System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
           在 System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
           在 System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
           在 System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
           在 System.Windows.Forms.Application.Run(Form mainForm)
           在 BookStore.Program.Main() 位置 D:\Backup\我的文档\Visual Studio 2005\Projects\BookStore\BookStore\Program.cs:行号 17
           在 System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
           在 System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
           在 Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
           在 System.Threading.ThreadHelper.ThreadStart_Context(Object state)
           在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           在 System.Threading.ThreadHelper.ThreadStart()
      

  4.   

    经测试,以下代码未被执行,为什么会这样呢?   private void CustomerForm_Load(object sender, EventArgs e)
            {
                try
                {
                    conn = new SqlConnection
                    (ConfigurationManager.ConnectionStrings["BookStore.Properties.Settings.BookStoreConnectionString"].ConnectionString);
                    conn.Open();
                    cmd = new SqlCommand();
                    cmd.Connection = conn;
                 
                    this.InitData();
                }
                catch (Exception exp)
                {
                    MessageBox.Show("无法建立数据连接:" + exp.Message);
                    this.Close();
                }
            }
               
                private void CustomerForm_FormClosing(object sender, FormClosingEventArgs e)
                {
                    if (conn != null && conn.State != ConnectionState.Closed)
                        conn.Close();
                }
            protected void InitData()
            {
                cmd.CommandText = "select distinct [ID] from [Customer] order by [ID]";
                SqlDataReader reader1 = cmd.ExecuteReader();
                cmbCustomerID.Items.Clear();
                while (reader1.Read())
                    cmbCustomerID.Items.Add(reader1[0]);
                reader1.Close();
                
            }
      

  5.   

    不是在Load里面写了连接数据库的语句了吗?
    请问你的意思是怎么添加一个数据连接语句?
      

  6.   

    找到原因了,在这段里面加一句就可以了:
            public CustomerForm()
            {
                InitializeComponent();
                this.Load += new EventHandler(CustomerForm_Load);  
            }