I faced this question in my two interviews. If interviewer wants some more detailed answer from us they ask us to write the core logic. This question is
the basic logic of establishing the connection to database and fetch the records from it and assigning it to grid or some other data controls.
(Pls include the necessary namespaces, I couldn't add due to maximum character exceeding)
public partial class Example : System.Web.UI.Page
SqlConnection sqlCon = null;
protected void Page_Load(object sender, EventArgs e)
public void BindGridView()
sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM tbl_EmployeePrim";
cmd.Connection = sqlCon;
grdview.DataSource = ds;
catch (Exception exx)
if (sqlCon.State == ConnectionState.Open)
Here I have declared a function called BindGridView() which I called in !Ispostback condition. So that the data will not be fetched every time we refresh the page.In BindGridView() function I have written the connection string value from ConfigurationManager class. Now my sqlCon object contains ConnectionString value which we defined in WebConfig file.I have created Sqlcommand object, Dataadapter object and initialized with command object. I am assigning the select query in command object after createing dataset.
Assigning connection property of command with Sql connection object "sqlcon". Using Execute Reader method I am reading all the values of Employee table and fill the data to dataset object. Then I am binding the data set to gridview.
Important point to be noted is I am opening the connection only at the preivous line of ExecuteReader() and immediately closing the connection after ExecuteReader().This will improve the performance since establishing connection to the database is very costly operaion. One more thing is we should not directly use select query, insert or update query in the page. We need to use Stored procedure with input and output parameters to fetch or modify the database records. For example purpose I wrote Select query here which I did in my interview
Asked In: CTS |