0

I am trying to hit sql server with objectdatasource and return a datatable to fill my details view control. the selected ID value is returned by a gridview control. It seems like the datatable is not filled by adapter, and i couldn't figure out why. The ID in sql is set as a primary key (Int, 4, not null). The debugger says the Detail datatable is null. Any help is much appreciated.

public DataTable GetDetail(string ID)
        {
            if (ID == "")
            {
                return null;
            }
            else
            {

                DataTable Detail = null;
                using (SqlConnection conn = new SqlConnection(connection))
                {
                    string comm = @"select * from dbo.Products where ID = @ID";
                    conn.Open();
                    SqlDataAdapter adapter=null;
                    using (SqlCommand cmd = new SqlCommand(comm, conn))
                    {
                        cmd.Parameters.Add("ID", System.Data.SqlDbType.Int, 4).Value = Convert.ToInt32(ID);
                        adapter = new SqlDataAdapter(cmd);
                        adapter.Fill(Detail);
                        return Detail;
                    }
                }
            }
John
  • 190
  • 1
  • 4
  • 15

3 Answers3

0

I think you missed the commandType

cmd.CommandType = CommandType.Text;
Adil
  • 146,340
  • 25
  • 209
  • 204
0

Try this

DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection(connection))
 {
    string myquery="select * from dbo.Products where ID = @ID";
    SqlCommand cmd = new SqlCommand(myquery, con);
    SqlDataAdapter dap = new SqlDataAdapter();
    dap.SelectCommand = cmd;
    cmd.Parameters.Add("@ID", SqlDbType.NVarChar, 15).Value = ID;
    dap.Fill(ds);
    return ds.Tables[0];
  }
Satinder singh
  • 10,100
  • 16
  • 60
  • 102
0

Thanks for ALL.

The problem is I didnt initialize my datatable to a new instance.

DataTable Detail = null; ===> DataTable Detail = new Datatable();

and also the convert should be done in sql not in codes.

cmd.Parameters.Add("ID", System.Data.SqlDbType.Int, 4).Value = ID;

string comm = @"select * from dbo.Products where ID = convert(int,@ID)";

John
  • 190
  • 1
  • 4
  • 15