using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace 更新数据源//又问题    未完成
{
    public partial class Form1 : Form
    {
        SqlConnection conn;
        DataSet ds;
        SqlDataAdapter sda;
                public Form1()
        {
            InitializeComponent();
        }        private void Form1_Load(object sender, EventArgs e)
        {
            conn = new SqlConnection("server=.;database=practice;uid=sa;pwd=123123123");
            SqlCommand cmd = new SqlCommand("select * from student", conn);
            sda = new SqlDataAdapter();
            sda.SelectCommand = cmd;
            ds = new DataSet();
            sda.Fill(ds, "student");
            dataGridView1.DataSource = ds.Tables[0];
        }        private void button1_Click(object sender, EventArgs e)
        {
            DataTable dt = ds.Tables["student"];
            sda.FillSchema(dt, SchemaType.Mapped);
            DataRow dr = dt.Rows.Find(txtNo.Text);
            
            //dr["xuehao"] = txtNo.Text.Trim();
            dr["xingming"] = txtName.Text.Trim();
            dr["dianhua"] = txtTel.Text.Trim();
            SqlCommandBuilder cmdbuider = new SqlCommandBuilder(sda);
            sda.Update(dt);
        }        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            txtNo.Text = dataGridView1.SelectedCells[0].Value.ToString();
            txtName.Text = dataGridView1.SelectedCells[1].Value.ToString();
            txtTel.Text = dataGridView1.SelectedCells[2].Value.ToString();
        }
    }
}
这是一个更新数据源的问题:其中student表中有xuehao  xingming dianhua,xuehao 为主键
在运行中出现错误 :
               未将对象引用设置到对象的实例。
哪位大虾帮帮小弟吧

解决方案 »

  1.   

     private void button1_Click(object sender, EventArgs e)
      {
      DataTable dt = ds.Tables["student"];
      sda.FillSchema(dt, SchemaType.Mapped);应该是这里的问题。。
      DataRow dr = dt.Rows.Find(txtNo.Text);
        
      //dr["xuehao"] = txtNo.Text.Trim();
      dr["xingming"] = txtName.Text.Trim();
      dr["dianhua"] = txtTel.Text.Trim();
      SqlCommandBuilder cmdbuider = new SqlCommandBuilder(sda);
      sda.Update(dt);
      }
      

  2.   

    FillSchema是用来向DataTable中填入详细的元数据信息的,例如(column names, primary key, constraints等),但不填入数据。 
    Fill主要是用来填入数据的,它在缺省情况下只填入少量必要的元数据信息,例如(column names, data types)。 
    所以,一般先用FillSchema来填入详细的元数据信息,再用Fill来填充数据,例如:sqlDataAdapter1.FillSchema(dataSet1,SchemaType.Source,"authors"); 
    sqlDataAdapter1.Fill(dataSet1,"authors");
      

  3.   

    sda.FillSchema(dt, SchemaType.Mapped);去掉就行。
      DataTable dt = ds.Tables["student"];  //设置个断点:看看dt是不是null
      sda.FillSchema(dt, SchemaType.Mapped);
      DataRow dr = dt.Rows.Find(txtNo.Text);错误提示应该是:null值然后用了运算符 .