简体   繁体   中英

How to display a specific data from a database into textbox?

public DataTable DisplayHolidays(int empid)
{
    DataTable dt = new DataTable();

    SqlCommand cmd = new SqlCommand("ComputeHoliday", myCon);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("@EmployeeID", SqlDbType.Int).Value = empid;
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    da.Fill(dt);
    SqlDataReader rd = cmd.ExecuteReader();

    while (rd.Read())
    {
        temp2 = rd[0].ToString();
    }
    return dt;
}

This is my code I had a problem/error with this part. This code is in the class not in the form load. It cannot display the data in the textbox. I'm using temp2 to store the data in the selected row but it's not yet working.

I assume that you're getting an exception at cmd.ExecuteReader() .

Note that you must open the connection before you can use the command in cmd.ExecuteReader() . DataAdapter.Fill does not need an open connection, the dataadapter will open/close it implicitly.

MSDN :

The connection object associated with the SELECT statement must be valid, but it does not need to be open. If the connection is closed before Fill is called, it is opened to retrieve data, then closed. If the connection is open before Fill is called, it remains open.


Why do you use DataAdapter.Fill(DataTable) and also Command.ExecuteReader ? You need just one way to get the data. If you already have filled a table:

If(dt.Rows.Count > 0)
{
    temp2 = dt.Rows[0].Field<string>(0);
}

If you don't use the DataAdapter and the DataTable but only the reader:

using(SqlDataReader rd = cmd.ExecuteReader())
{
    if(rd.HasRows)
    {
        rd.Read();
        temp2 = rd.GetString(0);
    }
}

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