将Textbox事件从Form传递给Class时的Null引用

时间:2015-01-21 06:38:19

标签: c# winforms forms events textbox

我有以下代码:

表格中:

public void filterType_TextChanged(object sender, EventArgs e)
    {
        var dSearch = new D_Search(this);
        dSearch.filterD(sender);
     }

所以我有一个Textbox事件,我在另一个类dSearch中调用filterD函数。在dSearch课程中我有:

    public D_Search(Form1 frm1)
    {
        form1 = frm1;
    }

      public String filterD(object sender)
    {
        string val = String.Empty;

        if (sender == form1.filterType())
        {
            val = (sender as TextBox).Text;
           //havent written the whole SQL Command here
            sqlCmd = new SqlCommand("SELECT * FROM, connection); 
        }

        datTable = new DataTable();
        sqlDatAdapter = new SqlDataAdapter(sqlCmd.CommandText,
        connection); //causes NullReferenceException
        sqlDatAdapter.Fill(datTable);

        form1.setDataGrid = datTable;

        return val;
    }

所以我的表单中有多个函数,比如filterType,它们是Textbox事件。现在我想将它们传递给我的Class,它应该注意if语句调用了什么事件(Textbox被更改了)但是我在sqlDatAdapter处获得了NullReference异常。我该怎么办?

编辑:这是空的cmd。此外:

这是filterType函数:

   public String filterType()
    {
        return filterTypeNumber.Text;
    }

EDIT2:未使用if语句,因此他无法识别发件人,因为他会比较发件人是否为文本框条目。我该怎么办?

3 个答案:

答案 0 :(得分:1)

所以将你的IF语句改为;

if ( (sender as TextBox).Text== form1.filterType())
    {

       //havent written the whole SQL Command here
        sqlCmd = new SqlCommand("SELECT * FROM, connection); 
    }

还要确保连接已打开。

希望它有所帮助...... !!!

答案 1 :(得分:0)

您没有打开连接

 Con.OPen();    
 //logic here
 cmd.ExecuteNonQuery();
 Con.Close();

//数据驻留在sqlCmd对象

sqlCmd = new SqlCommand("SELECT * FROM, connection);

尝试将sqlCmd作为参数传递

sqlDatAdapter = new SqlDataAdapter(sqlCmd,connection); 

答案 2 :(得分:0)

确保您已实例化connection,因此它不为空。假设这不是你的问题,在我看来你可能会从sqlCmd获得NullRefEx,当(sender == form1.filterType())为false时可能无法实例化。如果是这样,你应该能够通过稍微改变一下来解决它,例如:

// Make the table available outside the if-else, even if it is empty:
datTable = new DataTable(); 

if (sender == form1.filterType())
{
    val = (sender as TextBox).Text;
    //havent written the whole SQL Command here
    sqlCmd = new SqlCommand("SELECT * FROM, connection); 

    // Only do this if it is relevant, i.e. here within the if-structure,
    // that way, you should be able to avoid the nullRef:
    sqlDatAdapter = new SqlDataAdapter(sqlCmd.CommandText, connection); 
    sqlDatAdapter.Fill(datTable);
}

// You might have to check something extra here, depending on
// usage, since the table might be empty:
form1.setDataGrid = datTable;

回复评论时更新:

我不确定我是否会关注您,但如果您想再次移出sqlCmd,那很好 - 只要确保它不为空,即使sender == form1.filterType()为false。如果在实例化sqlCmd.CommandText之前还有其他内容填充SqlDataAdapter,请确保先执行此操作。否则,您可能会执行以下操作,并将所有这些放在另一个if - 结构之外:

if(sqlCmd != null && !String.IsNullOrEmpty(sqlCmd.CommandText)){
    sqlDatAdapter = new SqlDataAdapter(...)
    ...
}

无论哪种方式,您都必须通过以下两种方式之一来避免空引用:填充sqlCmd,因此它不为空,或者避免调用它。

相关问题