首页 > 解决方案 > 如何将空文本框设置为空

问题描述

您好我正在创建一个 RDLC 报告,并且我有来自 sql 数据库的搜索条件的文本框,所以我想将所有空文本框设置为 null,以便根据 sql 查询生成报告

我怎样才能做到这一点


private void button1_Click(object sender, EventArgs e)
    {
        string FNAME, LNAME, ID, COMPANY, INVITER, LOCATION;
        FNAME = textBoxFname.Text;
        LNAME = textBoxLname.Text;
        ID = textBoxIqama.Text;
        COMPANY = textBoxCompany.Text;
        INVITER = textBoxInviter.Text;
        LOCATION = textBoxLocation.Text;
        { 
            if (textBoxFname.Text == "") 
            {
                FNAME = null;
            } 
          }  
            if (textBoxLname.Text == "") 
            {
                LNAME = null;
            }

            if (textBoxIqama.Text == "")
            {
                ID = null;
            }

            if (textBoxCompany.Text == "") 
            {
                COMPANY = null;
            }

            if (textBoxInviter.Text == "") 
            {
                INVITER = null;
            }

            if (textBoxLocation.Text == "") 
            {
                LOCATION = null;
            }


    }

    private void button2_Click(object sender, EventArgs e)
    {
        this.visitorreportTableAdapter.Fill(this.Companysearch.visitorreport, dateTimePicker1.Value, dateTimePicker2.Value, FNAME, LNAME, ID, COMPANY, INVITER, LOCATION);

        this.reportViewer1.RefreshReport();
    }

标签: c#

解决方案


不确定其他类型的文本框,但在 Winforms 中,Texta 的属性TextBox将永远不会返回null。也许最简单的方法是为此编写一个辅助函数:

public static string GetTextNullIfEmpty(string input)
{
    return string.IsNullOrEmpty(input) ? null : input;
}

然后你可以像这样实现它:

string FNAME = GetTextNullIfEmpty(textBoxFname.Text);

此外,在方法内声明的变量仅适用于该方法。因此,您不能从内部访问FNAME声明的变量。解决此问题的一种方法是将这些变量声明为类字段,以便类中的所有方法都可以访问它们:button1_Clickbutton2_Click

public partial class Form1 : Form
{
    // Declare FNAME at class level so all methods can access it
    private string FNAME;

    private void button1_Click(object sender, EventArgs e)
    {
        // Assign a value to FNAME
        FNAME = GetTextNullIfEmpty(textBoxFname.Text);
    }

    private void button2_Click(object sender, EventArgs e)
    {
        // Do something with FNAME here
    }
}

推荐阅读