c# - 不想在 C# 表单中插入空数据
问题描述
我制作了一个 SQL 数据库和一个 C# 表单。表格工作正常。当我从表单发送数据时,数据会正确插入到表中。但是我试过了,如果表格只有一个字段或者是空的,不要把数据发送到表中。我准备不允许表字段中的空数据。但除了主键之外,我可以为其他字段插入空数据。
这是我的主要表单代码。请改正
private void Form1_Load(object sender, EventArgs e)
{
txtPassword.PasswordChar = '*';
txtPasswordNew.PasswordChar = '*';
gboxSignup.Visible = false;
}
private void btnOrSignup_Click(object sender, EventArgs e)
{
gboxSignup.Visible = true;
}
private void btnSignupNew_Click(object sender, EventArgs e)
{
if (txtFirstNameNew.Text != null && txtLasyNameNew.Text != null && txtUserNameNew.Text != null && txtPasswordNew.Text != null && txtEmailNew.Text != null)
{
try
{
Connect obj = new Connect();
obj.conn.ConnectionString = obj.locate;
obj.conn.Open();
String insertUser = "insert into userTable values ('"+txtFirstNameNew.Text+ "','" +txtLasyNameNew.Text+ "','" +txtEmailNew.Text+ "','" +txtUserNameNew.Text+ "','" +txtPasswordNew.Text+"')";
obj.cmd.Connection = obj.conn;
obj.cmd.CommandText = insertUser;
obj.cmd.ExecuteNonQuery();
MessageBox.Show("Signup has been completed");
gboxSignup.Visible = false;
txtFirstNameNew.Text = "";
txtLasyNameNew.Text = "";
txtEmailNew.Text = "";
txtPasswordNew.Text = "";
txtUserNameNew.Text = "";
}
catch (Exception ex)
{
MessageBox.Show("ERROR" + ex);
}
}
else
{
MessageBox.Show("ERROR!!! Fill in the All Fields");
}
}
private void btnLogin_Click(object sender, EventArgs e)
{
if(txtUserName.Text != null && txtPassword.Text != null)
{
try
{
Connect obj = new Connect();
obj.conn.ConnectionString = obj.locate;
obj.conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter ("SELECT COUNT (*) FROM userTable where UserName = '" +txtUserName.Text+"' and Password = '"+txtPassword.Text+"' ", selectConnection: obj.conn );
DataTable dt = new DataTable();
adapter.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
frmWelcome meLoad = new frmWelcome();
meLoad.Visible = true;
this.Hide();
MessageBox.Show("Sucessfully Login");
}
else
{
MessageBox.Show("User Name Or Password is incorrect - Try it");
}
obj.conn.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else
{
MessageBox.Show("No Empty Field Allowed");
}
}
}
}
这是连接类代码
class Connect
{
public SqlConnection conn = new SqlConnection();
public SqlCommand cmd = new SqlCommand();
public string locate = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='J:\D Drive\Excersize\C#\Windowsform\WindowsFormsApp1\UserDB.mdf';Integrated Security=True";
}
解决方案
文本框的字符串不是空的,它只是空的。所以数据库可以插入它。!string.IsNullOrEmpty(text)
改为使用text != null
推荐阅读
- postgresql - 摄取完成后的 citus 写入活动
- oracle - 尝试确定异步作业何时完成:调用 Oracle 的 dbms_job.submit
- nginx - 多个服务的 NGINX 配置覆盖一个配置的 add_header
- swift - 自定义 UIBarButtonItem 不适用于外观
- java - 使用基准测试时的 Optaplanner OptaPlannerXmlSerializationException
- spring-webflux - WebClient - 如何忽略特定的 HTTP 错误
- javascript - Safari 比其他浏览器慢得多
- swift - NSTableView,didSelectRowAt 没有被击中
- sql - 删除按日期重复的记录,保留最旧的
- typescript - Nextjs 路径名中的查询参数正在被解码