开发者

SqlDataReader to string[]

开发者 https://www.devze.com 2023-02-18 03:49 出处:网络
why the following code doesn\'t work? internal static string[] GetToolsForRole(string selectedRole) { string[] tempStr;

why the following code doesn't work?

internal static string[] GetToolsForRole(string selectedRole) {
  string[] tempStr;
  ArrayList myAL = new ArrayList();
  SqlCommand cmd = new SqlCommand("usp_TD_SelectByRoleName");
  cmd.CommandType = CommandType.StoredProcedure;

  cmd.Parameters.Add("@role", SqlDbType.NVarChar, 50).Value = selectedRole;

  SqlConnection myConnection = Util.Ge开发者_如何学JAVAtConnection();
  cmd.Connection = myConnection;
  SqlDataReader reader = cmd.ExecuteReader();

  int i = 0;
  while (reader.Read()) {
    tempStr[i] = reader["TD_Name"].ToString();
    i++;
  }

  return tempStr;
}


Arrays don't work like that.

You should use a List<string>, and call the Add method.

To use an array,you need to create a new array by writing tempStr = new string[size]. Arrays cannot be resized in-place.


You never allocate tempStr.

Try this in loop:

myAL.Add(reader["TD_Name"].ToString());

Then this at return

return (String[]) myAL.ToArray( typeof( string ) );

You won't need (remove) the i and tempStr variables.

0

精彩评论

暂无评论...
验证码 换一张
取 消