我是 C# 和 Grid 的新手,我在 SQL 中有一个表,其中包含两列,Particulars 和 Price 以及每边的几个值。另一方面,在 C# win.form 网格上,有两列 Particulars 和 grid。当用户在 column1(详细信息)中输入任何数据并且输入的数据与 Table Particular 的值中的值不匹配时,它应该抛出异常。为此,我使用了 CellEndEdit 事件,但是在用户在空单元格中输入数据后,如何根据 DB 表值检查输入的数据是否正确。
我已经成功地将表单与 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();
// }
//}
}
}
}
}