2

I want to assign a value parameter dynamic through an array. For example, the array arr_param will contain two value [0] = "abc", [1] = "ZYX" .Now, I will assign them .The problem here is that i must specify the correct elements [0],[1] after run foreach, I tried do it but failed convert to int

string[] arr_param  =  array_parameter.Split(';');
foreach (DataRow parmRow in parmsDataTable.Rows)
{
    string parmName = parmRow[parmNameDataColumn].ToString();
    cmd.Parameters.AddWithValue(parmName, arr_param[Convert.ToInt32(parmsDataTable.Rows)]);
}

I get error Unable to cast object of type 'System.Data.DataRowCollection' to type 'System.IConvertible'.

1
  • 1
    You get this exception because of this line : cmd.Parameters.AddWithValue(parmName, arr_param[Convert.ToInt32(parmsDataTable.Rows)]); You're trying to convert a collection of DataRow which is parmsDataTable.Rows to an Int32 type. You can't do that convertion. Commented May 7, 2016 at 13:46

1 Answer 1

1

parmsDataTable.Rows is a DataRowCollection and it can't be converted to int.

A Simple Solution:

string[] arr_param  =  array_parameter.Split(';');
int counter = 0;
foreach (DataRow parmRow in parmsDataTable.Rows)
{
   string parmName = parmRow[parmNameDataColumn].ToString();
   cmd.Parameters.AddWithValue(parmName, arr_param[counter++)]);
}

Or:

string[] arr_param  =  array_parameter.Split(';');
foreach (DataRow parmRow in parmsDataTable.Rows)
{
   string parmName = parmRow[parmNameDataColumn].ToString();
   cmd.Parameters.AddWithValue(parmName,arr_param[parmsDataTable.Rows.IndexOf(parmRow))]);
}
Sign up to request clarification or add additional context in comments.

1 Comment

oh,two ways work and I think the first way easier to understand because it is clear.Thank you so much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.