如何从数据库中获取数据到文本框 [英] how to get data to textbox from the database
问题描述
我有一个包含一个组合框和文本框的表单,以及一个 SQL 数据库命名为 balance
有两列;一个为 customername
,另一个为 obbalance
.我已将所有客户名称绑定到组合框,现在我要做的是,当用户从组合框中选择客户名称时,文本框应显示所选customername
的obbalance;在这里,不会重复客户名称 - 每个客户只有一个名称.我能做什么?请帮帮我.
I have a form with one combo box and text box, and an SQL database
named balance
with two columns; one as customername
and the other as obbalance
.
I had bound all of the customer name to the combo box, now what I have to do is,
when a user selects a customer name from the combo box, the text box should show the obbalance of the selected customername
; here, the customer name will not be repeated - only one name per customer.
What can I do? Please help me.
Dim conectionstring As String
conectionstring = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\Projects\SHOPPROJECT\SHOPPROJECT\shop.mdf;Integrated Security=True;User Instance=True"
Dim ST As String = ComboBox1.SelectedText
Dim sqlcon As New SqlConnection(conectionstring)
Dim sqlcmd As New SqlCommand("SELECT OBBALANCE FROM BALANCE WHERE CUSTOMERNAME = " & " '" & ST & "'" & "", sqlcon)
MessageBox.Show(TextBox1.Text)
Dim result As Object
Try
sqlcon.Open()
' Dim sdr As SqlDataReader = sqlcmd.ExecuteReader()
result = sqlcmd.ExecuteScalar()
If result IsNot Nothing Then
TextBox1.Text = result.ToString()
MessageBox.Show(TextBox1.Text)
End If
Catch ex As SqlException
MessageBox.Show(ex.Message)
End Try
End Sub
我已经试过了,但是我看不到文本框中的值,而且 obbalance 是来自 SQL 数据库的浮点值.
I've tried this, but I can't see the value in the text box, and obbalance is a floating-point value from the SQL database.
推荐答案
设置断点并确保您获得 OBBALANCE 的值(看看您是否获得了任何行周期可能是好的).此外,确保您只能获得一行,因为您正在向前迭代,即使您只需要一个值.
Set a breakpoint and ensure you are getting the value for OBBALANCE (see if you are getting any rows period might be good). Also, make sure you can only get one row, as you are iterating forward, even when you only need one value.
更好的是,考虑 ExecuteScalar,它只返回一个值.在此期间,请参数化 SQL 查询,以免 SQL 注入.
Better yet, consider ExecuteScalar, which only returns a single value. While you are at it, parameterize the SQL query so you don't get SQL injected.
更新:只需在此处更改:
UPDATE: Just change it here:
sdr = sqlcmd.ExecuteReader()
sdr = sqlcmd.ExecuteReader()
类似的东西
Dim s as String = sqlcmd.ExecuteScalar()
Dim s as String = sqlcmd.ExecuteScalar()
然后使用 s 作为您的文本框值.您可能需要 ToString() 值或以其他方式转换为字符串,因为我相信 ExecuteScalar() 返回一个对象.
Then use s as your textbox value. You may have to ToString() the value or otherwise cast as string, as I believe the ExecuteScalar() returns an object.
这篇关于如何从数据库中获取数据到文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!