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.... :(
}
}
After this answer u will arise many good questions to used in answer like
Use of var ( http://msdn.microsoft.com/en-us/library/bb383973.aspx )
Use of using block ( http://msdn.microsoft.com/en-us/library/yh598w02(v=vs.80).aspx )
Using sqldataadpater class
Exception handling ( there are many ways u can use log4net )
and many more
No comments:
Post a Comment