VS2008 更新数据源问题

静之深 2010-07-22 12:48:40
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 为主键
在运行中出现错误 :
未将对象引用设置到对象的实例。
哪位大虾帮帮小弟吧
...全文
79 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
malun666 2010-07-22
  • 打赏
  • 举报
回复
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值然后用了运算符 .


福来哥 2010-07-22
  • 打赏
  • 举报
回复
FillSchema是用来向DataTable中填入详细的元数据信息的,例如(column names, primary key, constraints等),但不填入数据。
Fill主要是用来填入数据的,它在缺省情况下只填入少量必要的元数据信息,例如(column names, data types)。
所以,一般先用FillSchema来填入详细的元数据信息,再用Fill来填充数据,例如:

sqlDataAdapter1.FillSchema(dataSet1,SchemaType.Source,"authors");
sqlDataAdapter1.Fill(dataSet1,"authors");

a13623127108 2010-07-22
  • 打赏
  • 举报
回复
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);
}

110,539

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧