This is the optimized code to bind a gridview in asp.net in C#. As all know it is most favorite question in interview so answer it with optimization
private static void Fn_GridBInd()
{
try
{
using (var odt = new DataTable())
{
using (var ocon = new SqlConnection("Data Source=121.0.0.1; Initial catalog=master; User ID=sa; pwd=admin"))
{
using (var od = new SqlDataAdapter("select * from sys.tables", ocon))
{
od.Fill(odt);
}
}
if (odt.Rows.Count > 0)
{
//Bind the gridview with smile :)
}
}
}
catch (Exception ex)
{
//Handle the exception.... :(
}
}