从Datatable中查找条目

时间:2013-12-17 09:16:15

标签: vb.net sql-server-2008

我有一个带有TextBox的WinForm。
当我激活TextBox.Leave事件时,我需要检查我的TextBox.text(列,而不是行)中的条目DataSet是否存在该条目,如果不是,我只需要获得{{1} 1}}并且不应该允许将其提交到DataBase。

5 个答案:

答案 0 :(得分:1)

尝试此代码,我为您重现它,它正常工作...双重检查您在文本框中输入的值...

Public Class Form1
Dim table As DataTable
Dim ds As DataSet
Private Sub TextBox1_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.Leave

    Dim result() As DataRow = ds.Tables(0).Select("Name = '" + TextBox1.Text.Trim() + "'")
    If (result.Length > 0) Then
        MsgBox("Value Exist")
    Else
        'do your calculation
    End If
End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    table = New DataTable("Players")

    ' Add two columns.
    table.Columns.Add(New DataColumn("Name", GetType(String)))
    table.Columns.Add(New DataColumn("age", GetType(String)))
    ds.Tables(0).Select()

    table.Rows.Add("Magesh", "25")
    table.Rows.Add("flook", "22")
    ds.Tables.Add(table);


End Sub
End Class

答案 1 :(得分:0)

您可以将sql查询编写为tablename中的select cols,其中col ='yourtextboxvalue' 使用commandObject.executeReader执行datareader并在try块中执行dataReader.Read()方法。如果值不存在,它将转到catch块并在那里显示消息框。 检查用户名

的类似事情
SqlCommand command = new SqlCommand("Select Password from tblUser where UserName=@username", connection);
            command.Parameters.AddWithValue("@username", txtUsername.Text);     //add parameter to the query

 if (dataReader.Read())      //if any record is available
            {
                dbPassword = dataReader["Password"].ToString();     //get the password for entered username
                if (dbPassword != "" && dbPassword.Equals(password))        
                {

                }

                else
                    MessageBox.Show("Invalid Password","Invalid input");
                connection.Close();     //close the connection
            }

            else 
                MessageBox.Show("Username not found", "Invalid input");     //message will be shown if no record found for the entered user ie.username doesn't exist

答案 2 :(得分:0)

从数据库的角度来看,防止重复条目进入列的最简单方法是在给定列上设置唯一约束:

CREATE TABLE table1
(
Id int NOT NULL,
Name varchar(255) NOT NULL,
CONSTRAINT uc_Name UNIQUE (Name)
) 

答案 3 :(得分:0)

将此代码放入textbox1 leave事件

Dim result() As DataRow = DataTable.Select("ColumnName = '" + TextBox1.Text.Trim() + "'")

并且如果result.length> 0然后不保存....

答案 4 :(得分:0)

因为你提到DataSet试试这个(数据集不是表而是表的集合)

Dim Tot() as DataRow = yourDataset.Tables("tableName").Select("theColName= '" + TextBox.Text.Trim() + "'")

Dim Tot() as DataRow = yourDataset.Tables(IndexNumberOfTable).Select("theColName= '" + TextBox.Text.Trim() + "'")