我想在国籍的信息表DataGrid中添加一个DropDownlist控件用来编辑时可以选择有效或无效,但是我的数据是从数据库里取出来的,我在绑定时报以下错误:
未将对象引用设置到对象的实例。 
说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。 异常详细信息: System.NullReferenceException: 未将对象引用设置到对象的实例。源错误: 
行 78:  if(dd1!=null)
行 79:  {
行 80:  bool bflag = (bool)ds.Tables["country"].Rows[dgi.ItemIndex]["flag"];
行 81:  if(bflag)
行 82:  dd1.SelectedIndex = 0;
 源文件: c:\inetpub\wwwroot\aspnet_purchase\supplier_country.aspx.cs    行: 80 我的程序是:public void BindGrid()
{
          

       SqlConnection con=new SqlConnection("server=260915-F611EC1C;uid=sa;pwd=sa;DATABASE=Purchase_Management");
con.Open();
string strsql="select * from country";
SqlDataAdapter da=new SqlDataAdapter(strsql,con);
DataSet ds=new DataSet();
da.Fill(ds);
Dgd_country.DataSource=ds; Dgd_country.DataBind();
foreach(DataGridItem dgi in Dgd_country.Items)
{
//以下绑定非编辑状态下拉列表 
DropDownList dd1 = (DropDownList)dgi.FindControl("ddl_effective1");
if(dd1!=null)
{
bool bflag = (bool)ds.Tables["country"].Rows[dgi.ItemIndex]["flag"];
if(bflag)
dd1.SelectedIndex = 0;
else
dd1.SelectedIndex = 1;
}
//以下绑定编辑状态下拉列表 
DropDownList dd2 = (DropDownList)dgi.FindControl("ddl_effective2");
if(dd2!=null)
{
bool bflag = (bool)ds.Tables["country"].Rows[dgi.ItemIndex]["flag"];
if(bflag)
dd2.SelectedIndex = 0;
else
dd2.SelectedIndex = 1;
}

}
}

解决方案 »

  1.   


    这段话去掉..foreach(DataGridItem dgi in Dgd_country.Items) 

    //以下绑定非编辑状态下拉列表  
    DropDownList dd1 = (DropDownList)dgi.FindControl("ddl_effective1"); 
    if(dd1!=null) 

    bool bflag = (bool)ds.Tables["country"].Rows[dgi.ItemIndex]["flag"]; 
    if(bflag) 
    dd1.SelectedIndex = 0; 
    else 
    dd1.SelectedIndex = 1; 

    //以下绑定编辑状态下拉列表  
    DropDownList dd2 = (DropDownList)dgi.FindControl("ddl_effective2"); 
    if(dd2!=null) 

    bool bflag = (bool)ds.Tables["country"].Rows[dgi.ItemIndex]["flag"]; 
    if(bflag) 
    dd2.SelectedIndex = 0; 
    else 
    dd2.SelectedIndex = 1; 
    } } 在页面下直接将你要绑定的列绑定到 DropDownList 控件上
    <asp:DropDownList id="ddl_effective1" runat="server" selectedvalue=<%# Eval("要绑定的列名 flag")%> >
    <asp:ListItem Value="0">无效</asp:ListItem>
    <asp:ListItem Value="1">有效</asp:ListItem>
    </asp:DropDownList>再在你要获取值是用
    foreach(DataGridItem dgi in Dgd_country.Items) 
    {
    DropDownList dd1 = dgi.FindControl("ddl_effective1") as DropDownList ; 
    这是取值给你要的变量就可以了 如:flag=dd1.selectedValue;
    }
      

  2.   

    还是不行哦,报错说flag不能这样赋值
      foreach(DataGridItem dgi in Dgd_country.Items)  
                    { 
                          DropDownList dd1 = dgi.FindControl("ddl_effective1") as DropDownList ;  
                             flag=dd1.selectedValue; 
                    } c:\inetpub\wwwroot\lianxi16\Supplier_country.aspx.cs(106): 名称“flag”在类或命名空间“lianxi16.Supplier_country”中不存在