我的代码块出错,我需要帮助才能摆脱它。 [英] Error in my code block, I need help to get rid of it.

查看:111
本文介绍了我的代码块出错,我需要帮助才能摆脱它。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个代码在昨天但今天工作的地方,给出错误没有给出一个或多个必需参数的值。我不知道我做了什么。



我使用mClass类中的动态方法DBeditor将数据从窗体formA传递到Microsoft Access数据库。 br />

This codes where working yesterday but today, its giving error "No value given for one or more required parameters." I do not know what I have done.

I am passing data from window formA to Microsoft Access database using a dynamic method "DBeditor" in "mClass" class.

//DBeditor method in mClass.
public void DBeditor(string query, params Control[] A)
{
    static string path = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "\\dBase.accdb";

    OleDbCommand cmd = new OleDbCommand();
    OleDbDataAdapter adt = new OleDbDataAdapter();
    OleDbConnection con = new OleDbConnection(path);
    DataTable dt = new DataTable();
    DataSet ds = new DataSet();

    con.Open();
    cmd.Connection = con;
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = query;
    for (int i = 0; i < A.Length; i++)
    {
        cmd.Parameters.Add(new OleDbParameter(("@cell" + "[" + i.ToString() + "]"), OleDbType.VarChar)).Value = A[i].Text; //the problem is here.
        cmd.ExecuteNonQuery();
        con.Close();
    }
}

//Using DBeditor in Windows FormA
            mClass mcl = new mClass();
            mcl.DBeditor("Insert into AdministratorsTable ([SURNAME], [OTHER NAMES])values(@cell1, @cell2)",
                txtSName, txtONames);



请帮忙,我现在真的很困惑。


Please help, I am really confused right now.

推荐答案

我想执行应该在for循环之后进行。

I guess the execution should take place after the for loop.
for (int i = 0; i < A.Length; i++)
{
    cmd.Parameters.Add(new OleDbParameter(("@cell" + "[" + i.ToString() + "]"), OleDbType.VarChar)).Value = A[i].Text; //the problem is here.
    cmd.ExecuteNonQuery();
    con.Close();
}

cmd.ExecuteNonQuery();
con.Close();



如果 A.Length 为1,前面的代码将起作用但是当它超过1时,就会产生问题。


The previous code would work if the A.Length is 1. But when it exceeds 1, it would create problems.


这里的问题是你的参数名是 @ cell1 @ cell2 ,但在for循环中,您要为参数名称添加值,例如 @cell [1] @cell [2] 。你应该删除方括号。此外,您应该在循环外部放置 ExecuteNonQuery 关闭方法,否则在所有参数都具有值之前执行查询。

The problem here is that your parameter names are @cell1 and @cell2, but in your for loop, you are adding values to parameter names like @cell[1] and @cell[2]. You should remove the square brackets. Also, you should put the ExecuteNonQuery and Close method outside the loop, otherwise you execute the query before all parameters have values.
for (int i = 0; i < A.Length; i++)
{
    cmd.Parameters.Add(new OleDbParameter("@cell" + i.ToString(), OleDbType.VarChar)).Value = A[i].Text; // remove square brackets []
}
cmd.ExecuteNonQuery(); // put these two lines outside the loop
con.Close();


这篇关于我的代码块出错,我需要帮助才能摆脱它。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆