如何用SQL表中的数据验证DataGridView中用户输入的值

本文关键字:DataGridView 用户 输入 验证 数据 何用 SQL | 更新日期: 2023-09-27 18:10:38

我是c#和Grid新手,我有一个SQL表,其中包含两列,细节和价格和每一边的几个值。另一方面,c#赢了。窗体网格,有两列details和grid。当用户在列1(details)中输入任何数据时,如果输入的数据与Table Particular的value不匹配,则应该抛出异常。为此,我使用了CellEndEdit事件,但是在用户在空单元格中输入数据后,我如何检查输入的数据是否正确或不符合DB表值。

我已经成功地连接了数据库的形式,我成功地做到了这与VS的数据设置选项,但不知道如何做到这一点与SQL数据库,我已经尝试过,但我对验证与SQL数据库。这是我的代码:

namespace Small_Billing_System
{
public partial class hitbill : Form
{
    SqlConnection cn = new SqlConnection(@"server=people-pc'sqlexpress;integrated security=true;database=nec");
    SqlCommand cm = new SqlCommand();
    SqlDataAdapter da = new SqlDataAdapter();
    //da1, da2;
    // ds1, ds2;
    DataSet ds = new DataSet();
    SqlCommandBuilder cb = new SqlCommandBuilder();
    public hitbill()
    {
        InitializeComponent();
    }

    private void control()
    {
        //dataGridView_2.DataSource = ds;
        //dataGridView_2.DataMember = "tblfood";
        //totalbox.DataBindings.Add("Text", ds, "tblfood.Price");
    }

    private void hitbill_Load(object sender, EventArgs e)
    {
        SqlConnection cn = new SqlConnection(@"server=people-pc'sqlexpress;integrated security=true;database=nec");
        try
        {
            cn.Open();
            MessageBox.Show("Data base connected");
        }
        catch (Exception)
        {
            MessageBox.Show("Data base connection failed");
            throw;
        }
        cn.Open();
        cm = new SqlCommand("select * from tblfood", cn);
        da = new SqlDataAdapter(cm);
        da.Fill(ds, "tblfood");

    }
    private void dataGridView_2_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        DataGridViewCell currCell = dataGridView_2.CurrentCell;
        string currCellContent = currCell.Value.ToString();
        //    SqlCommand cmd = new SqlCommand("select * FROM tblfood");
        //check whether inputted values are in DB or not
        if (dataGridView_2.CurrentCell.ColumnIndex == 0)
        {
            //        if (!((currCellContent == ???????????????.
            //        if (!((currCellContent == "Beans") || (currCellContent == "Juice"))) //cannot do this because there might be many particulars not just 2 or 3
//And when there are many particulars every time when user inputs value it should be   checked with database and throw an exception/error in case of wrong input.
            //        {
            //            MessageBox.Show("Paticulars not found");
            //            dataGridView_2.CurrentCell.Value = "";
            //        }
            //    }
            //    else if (dataGridView_2.CurrentCell.ColumnIndex ==1)
            //    {
            //         double R = 0.00;
            //        string particular =  dataGridView_2.CurrentRow.Cells[0].Value.ToString().Trim();
            //        if (particular == "Beans")
            //        {
            //            R = Double.Parse(currCellContent) * Properties.Data1.Default.Apple;
            //        }
            //        else if (particular == "Juice")
            //        {
            //            R = Double.Parse(currCellContent) * Properties.Data1.Default.Orange;
            //        }
            //        else
            //        {
            //            R = 0.00;
            //        }
            //        dataGridView_2.CurrentRow.Cells[2].Value = R.ToString();
            //        DataGridViewRowCollection rows = dataGridView_2.Rows;
            //        double total = 0.00;
            //        foreach (DataGridViewRow row in rows)
            //        {
            //            if (!row.IsNewRow)
            //            {
            //                double price = Double.Parse(row.Cells[2].Value.ToString());
            //                total = total + price;
            //            }
            //        }
            //        totalbox.Text = total.ToString();
            //    }
            //}
        }
    }
}
} 

如何用SQL表中的数据验证DataGridView中用户输入的值

我希望我没看错。

所以你有一个表在SQL充满数据?"详情"answers"价格"两栏?

你有一个Winform与Datagridview有相同的列?

您还连接了它,以便您可以执行查询?

那么我这样想对吗?

有几种方法可以做到这一点,简单快捷的方法是通过SQL检查。

创建一个简单的Select存储过程。

CREATE PROCEDURE [dbo].[ValidationResult]
@particular as varchar(50)
AS
SELECT Particulars, Price FROM Yourtable
WHERE Particulars = @particular

所以现在你需要做的就是设置链接。

public DataTable SQL_ValidateCheck(string part)
    {
        try
        {
            DataTable tbl_val = new DataTable();
            using (SqlConnection AutoConn = new SqlConnection(conn32))
            {
                AutoConn.Open();
                using (SqlCommand InfoCommand = new SqlCommand())
                {
                    using (SqlDataAdapter infoAdapter = new SqlDataAdapter(InfoCommand))
                    {
                        InfoCommand.Connection = AutoConn;
                        InfoCommand.CommandType = CommandType.StoredProcedure;
                        InfoCommand.CommandText = "dbo.ValidationResults";
                        InfoCommand.Parameters.AddWithValue("@particular", part);
                        InfoCommand.CommandTimeout = 180;
                        infoAdapter.Fill(tbl_val );
                        AutoConn.Close();
                        return tbl_val ;
                    }
                }
            }
        }
        catch (Exception e)
        {
            //MessageBox.Show("Error in connection :: " + e);
            return tbl_val ;
        }
    }

现在你有了一个表,里面有你的Validation Select查询的结果。

你最不需要做的就是使用它。

private void Check_Val()
{
    DataTable myTable = new DataTable();
    myTable = SQL_ValidateCheck(mygrid.CurrentSelection.Cells[0].Value.ToString());
    //Iterate the table for the result, maybe use an if(mytable == null) or something
}

可以在您的网格事件中使用此方法,完全由您决定。语法可能不正确,最近一直在使用Telerik,所以请检查语法,但您应该了解大意。