当前位置:编程学习 > C#/ASP.NET >>

DataRow报错。向cbo控件插入一条数据!初学者求高手帮忙看看!

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 Assets
{
     
    public partial class AddMoneyFrm : Form
    {

        DataSet ds = new DataSet();
        SqlDataAdapter sda = null;
       
        public AddMoneyFrm()
        {
            InitializeComponent();
        }

        private void AddMoneyFrm_Load(object sender, EventArgs e)
        {
            
            AddNewRowByCboType();    //向assets表的第一行添加数据“请选择类型”
            FillAssetsCboTyupe();    // 填充下拉列表cboType方法
            //绑定资产类型数据
            cboType.DataSource = ds.Tables["assets"];  
            cboType.ValueMember = "id";
            cboType.DisplayMember = "assetType";

           
        }

        private void AddNewRowByCboType()
        {
            //向assets表的第一行添加数据“请选择类型”
            DataRow  row = ds.Tables["assets"].NewRow();   // 此处报错:未将对象引用设置到对象的实例。
            row["id"] = -1;
            row["assetType"] = "请选择类型";
            ds.Tables["assets"].Rows.InsertAt(row, 0);
        }

        private void FillAssetsCboTyupe()
        {
            string sql = string.Format("select id,assetType from assets");
            sda = new SqlDataAdapter(sql, DBHelper.connection);
            sda.Fill(ds, "assets");

        }
    }
}
--------------------编程问答--------------------
一期要考试了   做机试练习出错 = = --------------------编程问答-------------------- 你的ds是空的

你先把返回的数据绑定给dataset --------------------编程问答-------------------- private void AddMoneyFrm_Load(object sender, EventArgs e)
        {
            
            FillAssetsCboTyupe();    // 填充下拉列表cboType方法
            AddNewRowByCboType();    //向assets表的第一行添加数据“请选择类型”
            //绑定资产类型数据
            cboType.DataSource = ds.Tables["assets"];  
            cboType.ValueMember = "id";
            cboType.DisplayMember = "assetType";

           
        } --------------------编程问答-------------------- DataRow  row = ds.Tables["assets"].NewRow();  // 此处报错:未将对象引用设置到对象的实例。 

要么 ds 为null, 要么ds.Tables["assets"]为null 了

在操作之前先判断一下是否为null --------------------编程问答-------------------- ds 先实例化后 再使用 --------------------编程问答-------------------- AddNewRowByCboType();
 FillAssetsCboTyupe(); 
把这俩 顺序换一下你在试试
补充:.NET技术 ,  组件/控件开发
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,