SqlDataReader to string[]
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.
精彩评论