简体   繁体   中英

Getting data out of a dataset

I am trying to get data out of an sql table using a dataset and a stored procedure, the dataset should only contain one value after the procedure is executed (I am getting id numbers, and id number is a primary key in my Costumers table so there should only be one of each). The IsCostumerIDTaken stored procedure just returns the id that it takes as a parameter. If it finds it, it returns it. I dont know what it does if it doesn't, returns 0 perhaps.

 public static bool IsCostumerIDTaken(string id)
    {
        SqlConnection conObj = GetConnection();
        SqlCommand cmdObj = new SqlCommand("IsCostumerIDTaken", conObj);
        cmdObj.CommandType = CommandType.StoredProcedure;
        cmdObj.Parameters.Add("@ID", SqlDbType.NVarChar).Value = id;        
        SqlDataAdapter da = new SqlDataAdapter(cmdObj);
        DataSet ds = new DataSet();
        da.Fill(ds);
        if (ds.Tables[0].Rows[0][0].ToString() != id)
            return false;
        return true;       
    }

after executing this command in one of my pages

Label1.Text = DAL.IsCostumerIDTaken(TextBox1.Text).ToString();

I get this error:

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IndexOutOfRangeException: There is no row at position 0.

 Source Error: Line 73: DataSet ds = new DataSet(); Line 74: da.Fill(ds); Line 75: if (ds.Tables[0].Rows[0][0].ToString() != id) Line 76: return false; Line 77: return true; 

What is the problem here, exactly? Am I not pulling data out of a dataset correctly?

If there is no data, there will be no rows. You need to test ds.Tables[0].Rows.Count

Replace this part

if (ds.Tables[0].Rows[0][0].ToString() != id)
            return false;
        return true;

with this:

return ds.Tables[0].Rows.Count > 0 && ds.Tables[0].Rows[0][0].ToString().Equals(id);

Correct. You are not pulling the data out correctly. It's impossible for me to tell, but somewhere in here...

ds.Tables[0].Rows[0][0]

... you are getting a null object. I would expect that the query is returning empty so the last [0] is trying to index a null .

If you have sufficient database permissions, you can run SQL Server Profiler on the database and see the exact query with the exact parameters that are being executed. From there, you should be able to determine if the problem is with your stored procedure or with your C# code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM