我创建了一个表单,将销售数据保存到数据库中,如果用户没有填写所有字段,它应该显示一条错误消息或只突出显示空文本框。我使文本框突出显示,如果空的,但一些文本框,如日期和两个组合框没有突出显示。如果文本框不为空,则保存数据,我已经编写了将数据保存到数据库的代码。我只是不知道如何构造else语句,使其在文本框不为空时保存数据。屏幕截图:https://snipboard.io/t5keMo.jpg
这是我的代码:
Public Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim txt As Control
Dim combo As New Control
' While
For Each txt In Panel1.Controls
If TypeOf txt Is TextBox Then
If txt.Text = "" Then
txt.BackColor = Color.Yellow
txt.Focus()
End If
End If
Next
For Each combo In Panel1.Controls
If TypeOf combo Is ComboBox Then
If combo.Text = "" And combo.Text = "" Then
combo.BackColor = Color.Yellow
combo.Focus()
End If
End If
Next
For Each Dt In Panel1.Controls
If TypeOf Dt Is Date Then
If Dt.Text = "" Then
Dt.BackColor = Color.Yellow
Dt.Focus()
End If
End If
Next
' End While
End Sub
保存数据:
Public Sub save_data()
' load_table()
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString = "server=localhost;userid=root;password=root;database=golden_star"
Dim READER As MySqlDataReader
Try
MysqlConn.Open()
Dim Query As String
If (MessageBox.Show("Do you want to save the changes?", "Save Changes", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes) Then
Query = "insert into golden_star.sales (date,brand,size,selling_unit_price,cost_unit_price,quantity,cost_of_goods,profit,total_cost_price) values ('" & DateTimePicker.Text & "','" & ComboBox1.Text & "', '" & ComboBox2.Text & "', '" & txtSelling.Text & "', '" & txtCostPrice.Text & "', '" & ComboBox3.Text & "', '" & txtTotalSell.Text & "', '" & txtProfit.Text & "',
'" & txtCp.Text & "')"
Command = New MySqlCommand(Query, MysqlConn)
MessageBox.Show("Daily Sales Entered Successfully")
READER = Command.ExecuteReader
MysqlConn.Close()
End If
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
End Sub
1条答案
按热度按时间ljsrvy3e1#
您一定要将正确的控件用于正确的数据类型。例如,不要将TextBox用于DateTimePicker,而要使用ErrorProvider来指示控件是否有任何错误。
下面是一个非常简单的例子: