在ASP.NET中,我在列表诓中绑定了一个字段,我想通过鼠标双击事件把这个值给取出来,可是就是不行.
第一种:string a =this.ListBox1.SelectedItem.Value.ToString();
       给出来的提示信息是:NullReferenceException: 未将对象引用设置到对象的实例
第二种:string a =this.ListBox1.SelectedValue.Trim().ToString();
       取出来的根本就是空
第三种:string a =this.ListBox1.DataTextField;
       取出来的也是空那位大侠能够帮我解决这个问题啊!感激!

解决方案 »

  1.   

    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Web;
    using System.Web.SessionState;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;namespace CS_WebTest
    {
    /// <summary>
    /// WebForm1 的摘要说明。
    /// </summary>
    public class WebForm1 : System.Web.UI.Page
    {
    protected System.Web.UI.WebControls.ListBox ListBox1;

    private void Page_Load(object sender, System.EventArgs e)
    {
    if (this.IsPostBack == false)
    {
    DataTable dtObj = new DataTable();
    dtObj.Columns.Add("Id");
    dtObj.Columns.Add("Name");
    DataRow drObj;
    for (int i=0;i<10;i++)
    {
    drObj = dtObj.NewRow();
    drObj[0] = i.ToString();
    drObj[1] = "Test" + i.ToString();
    dtObj.Rows.Add(drObj);
    }
    ListBox1.DataSource = dtObj;
    ListBox1.DataValueField = "Id";
    ListBox1.DataTextField = "Name";
    ListBox1.DataBind();
    }
    } #region Web 窗体设计器生成的代码
    override protected void OnInit(EventArgs e)
    {
    //
    // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
    //
    InitializeComponent();
    base.OnInit(e);
    }

    /// <summary>
    /// 设计器支持所需的方法 - 不要使用代码编辑器修改
    /// 此方法的内容。
    /// </summary>
    private void InitializeComponent()
    {    
    this.ListBox1.SelectedIndexChanged += new System.EventHandler(this.ListBox1_SelectedIndexChanged);
    this.Load += new System.EventHandler(this.Page_Load); }
    #endregion private void ListBox1_SelectedIndexChanged(object sender, System.EventArgs e)
    {
    Response.Write(ListBox1.SelectedValue + " : " + ListBox1.SelectedItem.Text);
    }
    }
    }
      

  2.   

    你绑定数据源时没有放在if (this.IsPostBack == false)里吧!
      

  3.   

    取Text 和 Value 分别为 ListBox1.SelectedItem.Text  ListBox1.SelectedValue
      

  4.   

    看看是否在postback时又绑定了这个列表框的数据.一般都是这个原因.
      

  5.   

    if (this.IsPostBack == false)
    {
       //绑定listbox
    }
      

  6.   

    鼠标双击事件?在ListBox中双击吗?
    好像没有这个事件,是不是要用JavaScript写啊
    如果是在其它事件中,首先在Page_Load()中要写
    if (!IsPostBack)
    {
    ListBox绑定代码,必须指定
    DataTextField  和DataValueField属性
    }
    取值就可以用ListBox1.SelectedValue了