Multidimensional array

M

Mike

Hi,

How can I declare and instantiate a multidimensional array that I need to return after having populated it from a DB. Here is the code:

string[,] g = new string[2,];
int i = 0;
while(rdr.Read())
{
g[0, i] = rdr.GetString(1) + " " + rdr.GetString(2);
g[1, i] = Convert.ToString(rdr.GetInt32(0)) + "~" +
rdr.GetString(3) + "~" +
rdr.GetString(4) + "~" +
rdr.GetString(5) + "~";
i++;
}

What is wrong with the above code? I try everything...

Thanks.
Mike
 
K

Ken Kolda

Arrays declared with square brackets are fixed-sized, not dynamic in the way you're trying to treat it. Use an ArrayList to dynamically add the rows to the array and then convert it over to a fixed-size array. For example,

ArrayList ga = new ArrayList();

int i = 0;
while (rdr.Read())
{
string[] gi = new string[2];
gi[0] = rdr.GetString(1) + " " + rdr.GetString(2);
gi[1] = Convert.ToString(rdr.GetInt32(0)) + "~" +
rdr.GetString(3) + "~" +
rdr.GetString(4) + "~" +
rdr.GetString(5) + "~" };
ga.Add(gi);
}

string[][] g = (string[][]) ga.ToArray(typeof(string[]));

Ken



Hi,

How can I declare and instantiate a multidimensional array that I need to return after having populated it from a DB. Here is the code:

string[,] g = new string[2,];
int i = 0;
while(rdr.Read())
{
g[0, i] = rdr.GetString(1) + " " + rdr.GetString(2);
g[1, i] = Convert.ToString(rdr.GetInt32(0)) + "~" +
rdr.GetString(3) + "~" +
rdr.GetString(4) + "~" +
rdr.GetString(5) + "~";
i++;
}

What is wrong with the above code? I try everything...

Thanks.
Mike
 
M

Mike

Thanks Ken.



Arrays declared with square brackets are fixed-sized, not dynamic in the way you're trying to treat it. Use an ArrayList to dynamically add the rows to the array and then convert it over to a fixed-size array. For example,

ArrayList ga = new ArrayList();

int i = 0;
while (rdr.Read())
{
string[] gi = new string[2];
gi[0] = rdr.GetString(1) + " " + rdr.GetString(2);
gi[1] = Convert.ToString(rdr.GetInt32(0)) + "~" +
rdr.GetString(3) + "~" +
rdr.GetString(4) + "~" +
rdr.GetString(5) + "~" };
ga.Add(gi);
}

string[][] g = (string[][]) ga.ToArray(typeof(string[]));

Ken



Hi,

How can I declare and instantiate a multidimensional array that I need to return after having populated it from a DB. Here is the code:

string[,] g = new string[2,];
int i = 0;
while(rdr.Read())
{
g[0, i] = rdr.GetString(1) + " " + rdr.GetString(2);
g[1, i] = Convert.ToString(rdr.GetInt32(0)) + "~" +
rdr.GetString(3) + "~" +
rdr.GetString(4) + "~" +
rdr.GetString(5) + "~";
i++;
}

What is wrong with the above code? I try everything...

Thanks.
Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top