c# - 如何将空文本框设置为空
问题描述
您好我正在创建一个 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();
}
解决方案
不确定其他类型的文本框,但在 Winforms 中,Text
a 的属性TextBox
将永远不会返回null
。也许最简单的方法是为此编写一个辅助函数:
public static string GetTextNullIfEmpty(string input)
{
return string.IsNullOrEmpty(input) ? null : input;
}
然后你可以像这样实现它:
string FNAME = GetTextNullIfEmpty(textBoxFname.Text);
此外,在方法内声明的变量仅适用于该方法。因此,您不能从内部访问FNAME
声明的变量。解决此问题的一种方法是将这些变量声明为类字段,以便类中的所有方法都可以访问它们:button1_Click
button2_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
}
}
推荐阅读
- angular - 如何在选定的离子选择上更改单选颜色
- r - 如何在 R 中使用 pivot_wider 填充 NA 值
- c# - 提取pdf矢量对象
- python - 如何在 python 中检查持久 ibm_db 连接的状态
- vue.js - 如何将默认类添加到vue中的第一个孩子
- sql - 基于值聚合对行进行分组
- linux - 如何在办公室支持列表中不可用的任何路由器上构建开源客户路由器固件
- amazon-web-services - 使用高级多部分上传仍然没有指定内容长度的警告
- algorithm - 试图弄清楚如何实现游戏的编队
- python - 比较数据的不同时间窗口以获得最相似的python