如果文本框为空,并且我将数据插入数据库,那么如何显示消息框?
private void button1_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "insert into Ученики (Имя,Класс,Группа) values ('" + textBox2.Text + "','" + comboBox1.Text + "','" + comboBox2.Text + "')";
command.ExecuteNonQuery();
MessageBox.Show("Data Saved");
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
答案 0 :(得分:0)
检查文本框的值是否为空:
private void button1_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(textBox2.Text))
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "insert into Ученики (Имя,Класс,Группа) values ('" + textBox2.Text + "','" + comboBox1.Text + "','" + comboBox2.Text + "')";
command.ExecuteNonQuery();
MessageBox.Show("Data Saved");
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
else
{
MessageBox.Show("textbox2 was empty!");
}
}
答案 1 :(得分:0)
您可以检查每个文本框是否有值。
private void button1_Click()
{
if (string.IsNullOrEmpty(textBox2.Text) || string.IsNullOrEmpty(comboBox1.Text) || string.IsNullOrEmpty(comboBox2.Text)
{
MesageBox.Show(@"Please enter text into each box.");
return;
}
// if all textboxes have values then call update the database
}
答案 2 :(得分:0)
您也可以使用javascript调用提醒框。
ASPX页面:
<script type="text/javascript" language="javascript">
function checkTextBoxEmpty() {
if (document.getElementById('<%=TextBox1.ClientId %>').value == "") {
alert("TextBox Empty.");
}
}
</script>
<asp:TextBox ID="TextBox1" runat="server" />
<asp:Button ID="Button1" runat="server" />
代码背后:
private void Page_Load(object sender, EventArgs e)
{
Button1.Attributes.Add("onClick", "javascript:checkTextBoxEmpty();")
}
private void Button1_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "insert into Ученики (Имя,Класс,Группа) values ('" + textBox2.Text + "','" + comboBox1.Text + "','" + comboBox2.Text + "')";
command.ExecuteNonQuery();
MessageBox.Show("Data Saved");
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}