且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

指数超出范围。必须是非负的且小于wpf中datagrid中集合的大小

更新时间:2022-06-13 06:15:41

可能在这里你收到错误:

Probably, you are getting the error here:
idlbl.Text = rd[0].ToString();

最可能的原因是没有符合您条件的记录:

And the most likely reason is that there are no records which match your condition:

SqlCommand cmod = new SqlCommand("Select catageoryId from catageory where catageoryName='" + textBlock2.Text + "'", con);

因此,请检查您的文本框是否包含您认为它的作用,并确保数据库确实具有匹配的行。事实上,***在运行时检查这个:

So check that your textbox contains what you think it does, and that the DB does have at leats one row which matches. In fact, it's best to check this at run time as well:

SqlCommand cmod = new SqlCommand("Select catageoryId from catageory where catageoryName='" + textBlock2.Text + "'", con);
rd = cmod.ExecuteReader();
if (rd.Read())
    {
    idlbl.Text = rd[0].ToString();
    ...

但请不要这样做!不要连接字符串以构建SQL命令。它让您对意外或故意的SQL注入攻击持开放态度,这可能会破坏您的整个数据库。请改用参数化查询:

But please, don't do it like that! Do not concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead:

SqlCommand cmod = new SqlCommand("Select catageoryId from catageory where catageoryName=@CN", con);
cmod.Parameters.AddWithValue("@CN", textBlock2.Text);
rd = cmod.ExecuteReader();
if (rd.Read())
    {
    idlbl.Text = rd[0].ToString();