Wednesday, August 19, 2009

Error Logging using ASP.NET 2.0

Error Logging using ASP.NET 2.0

This article has been republished with a few minor changes.
Errors and failures may occur during development and operation of a website. ASP.NET 2.0 provides tracing, instrumentation and error handling mechanisms to detect and fix issues in an application.
In this article, we will adopt a simple mechanism to log errors and exceptions in our website. We will be using a mechanism where the user will be redirected to a separate page whenever an error is encountered in the application. Simultaneously, the error will get logged in a text file on the server. The error file will be created on a daily basis, whenever the error is encountered. Having said that, let us now see some code.
Step 1: Start by creating an Error folder where all errors will be logged. Right click the website > New Folder. Rename the folder to “Error”. Also add a web.config file, if one does not already exist in your site. Right click the website > Add New Item > Web.config.
Step 2: Now we will create the error handler code. To do so, right click your website > Add New Item > select Class. Rename the class to ‘ErrHandler.cs’ and click on ‘Add’. When you do so, you will be prompted with a message to place the class in ‘App_Code’ folder. Accept the message to place the class in the 'App_Code' folder.
Step 3: Now let us add functionality to the ErrHandler class. This class will accept the error message and write the message in a text file. One text file will be created for each day. If the text file already exists, the message will be appended to the text file. If not, a new text file will be created based on today’s date and error message will be written in it.
The code will look similar to the following:
C#
/// Handles error by accepting the error message
/// Displays the page on which the error occured
public static void WriteError(string errorMessage)
{
try
{
string path = "~/Error/" + DateTime.Today.ToString("dd-mm-yy") + ".txt";
if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path)))
{
File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close();
}
using (StreamWriter w = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path)))
{
w.WriteLine("\r\nLog Entry : ");
w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
string err = "Error in: " + System.Web.HttpContext.Current.Request.Url.ToString() +
". Error Message:" + errorMessage;
w.WriteLine(err);
w.WriteLine("__________________________");
w.Flush();
w.Close();
}
}
catch (Exception ex)
{
WriteError(ex.Message);
}

}
VB.NET
''' Handles error by accepting the error message
''' Displays the page on which the error occured
Public Shared Sub WriteError(ByVal errorMessage As String)
Try
Dim path As String = "~/Error/" & DateTime.Today.ToString("dd-mm-yy") & ".txt"
If (Not File.Exists(System.Web.HttpContext.Current.Server.MapPath(path))) Then
File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close()
End If
Using w As StreamWriter = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path))
w.WriteLine(Constants.vbCrLf & "Log Entry : ")
w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture))
Dim err As String = "Error in: " & System.Web.HttpContext.Current.Request.Url.ToString() & ". Error Message:" & errorMessage
w.WriteLine(err)
w.WriteLine("__________________________")
w.Flush()
w.Close()
End Using
Catch ex As Exception
WriteError(ex.Message)
End Try

End Sub
That was our ErrHandler class. We will now see how to use this Error Handler class and handle errors at the page level as well as at the application level.
Handling errors at Page Level
In the Default.aspx, drag and drop a button from the toolbox. Rename this button to btnError and set the Text as ‘Throw Handled Exception’. Here we will throw an exception. Since we have a catch block defined, the exception will be caught and the error will be logged in the Error folder. Since a text file with today’s date, does not exists, a new text file will be created by the code.
The button click handler will look similar to the following:
C#
protected void btnHandled_Click(object sender, EventArgs e)
{
try
{
throw new Exception("Sample Exception");
}
catch (Exception ex)
{
// Log the error to a text file in the Error folder
ErrHandler.WriteError(ex.Message);
}
}
VB.NET
Protected Sub btnHandled_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnHandled.Click
Try
Throw New Exception()
Catch ex As Exception
' Log the error to a text file in the Error folder
ErrHandler.WriteError(ex.Message)
End Try
End Sub
Now with the code in place, run the application and click on the button. Since we have handled the error and logged the exception in our code, you will not notice anything when the button is clicked. However, close the application and refresh the Error folder. You will see a new text file created with today’s date. The exception has been logged successfully as shown below. The date and time will differ on your machine.
Log Entry :
01/11/2008 23:33:46
Error in: http://localhost:51087/ErrorHandling/Default.aspx. Error Message:Sample Exception
__________________________
Redirecting users on unhandled errors
Let us see how to catch unhandled errors and redirect the user to a different page, whenever such an unhandled error occurs at the application level.
To catch unhandled errors, do the following. Add a Global.asax file (Right click project > Add New Item > Global.asax). In the Application_Error() method, add the following code:
C#
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
Exception objErr = Server.GetLastError().GetBaseException();
string err = "Error in: " + Request.Url.ToString() +
". Error Message:" + objErr.Message.ToString();
// Log the error
ErrHandler.WriteError(err);
}
VB.NET
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when an unhandled error occurs
Dim objErr As Exception = Server.GetLastError().GetBaseException()
Dim err As String = "Error in: " & Request.Url.ToString() & ". Error Message:" & objErr.Message.ToString()
' Log the error
ErrHandler.WriteError(err)
End Sub
We capture the error using the Server.GetLastError(). Now to redirect users to a different page whenever an unhandled error occurs, open your web.config file and locate the tag and uncomment it. After removing the comment, the tag will look similar to the following code:



This configuration will now redirect the user to an Error page when an error occurs. Let us create this error page and display some message to the user.
Right Click Project > Add New Item> Create a new ErrorPage.aspx page in the application and display a sample message on the page informing the user that an error has occurred.
To test our functionality, go back to Default.aspx, add another button and rename it to btnUnhandled and set its Text property to ‘Throw Unhandled Exception’. Here instead of throwing the exception as we did for ‘btn_Error’, we will introduce a ‘Divide By Zero’ exception and not handle it. Observe that there is no try catch block as shown below. So when the error occurs, the user will be redirected to the ‘ErrorPage.aspx’ as a result of the changes made in our web.config file.
C#
protected void btnHandled_Click(object sender, EventArgs e)
{
try
{
throw new Exception("Sample Exception");
}
catch (Exception ex)
{
// Log the error to a text file in the Error folder
ErrHandler.WriteError(ex.Message);
}
}
VB.NET
Protected Sub btnUnhandled_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUnhandled.Click
Dim i As Integer = 1
Dim j As Integer = 0
Response.Write(i \ j)
End Sub

Run the application and click on the ‘Throw Unhandled Exception’ button. You will observe that the user will be automatically redirected to the Error Page and the error will be logged in the Error folder. Well that’s it.
In this article, we saw how to implement a simple error logging system in our application. Logging errors can be very useful and helps us detect errors during development and operation of a website. ASP.NET also provides some advanced options titled under ‘Health Monitoring’ where the errors can be stored in Sql Server or even emailed to the administrator based on the criticality of it.
I hope this article was useful and I thank you for viewing it

Finding gridview Header Row Control

Label lblCateName = (Label)(gvProductDtls.HeaderRow.FindControl("lblCateName"));
lblCateName.Text ="Category Name :: "+ Request.QueryString["cateName"].ToString();

Tuesday, August 18, 2009

merging two datasets in csharp

SqlConnection mySqlConnection =new SqlConnection("server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;");

SqlCommand mySqlCommand = mySqlConnection.CreateCommand();

mySqlCommand.CommandText =
"SELECT ID, FirstName, LastName, Address " +
"FROM Customers " +
"WHERE ID IN ('001', '002', '003')";
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
mySqlDataAdapter.SelectCommand = mySqlCommand;
DataSet myDataSet = new DataSet();
mySqlConnection.Open();
mySqlDataAdapter.Fill(myDataSet, "Customers");

mySqlCommand.CommandText =
"SELECT ID, FirstName, LastName, Address " +
"FROM Customers " +
"WHERE CustomerID IN ('008', '009')";
DataSet myDataSet2 = new DataSet();
mySqlDataAdapter.Fill(myDataSet2, "Customers2");

mySqlCommand.CommandText =
"SELECT TOP 5 ProductID, ProductName, UnitPrice " +
"FROM Products " +
"ORDER BY ProductID";
DataSet myDataSet3 = new DataSet();
mySqlDataAdapter.Fill(myDataSet3, "Products");

mySqlConnection.Close();

myDataSet.Merge(myDataSet2);

myDataSet.Merge(myDataSet3, true, MissingSchemaAction.Add);

foreach (DataTable myDataTable in myDataSet.Tables) {
Console.WriteLine("\nReading from the " + myDataTable + "DataTable");
foreach (DataRow myDataRow in myDataTable.Rows) {
foreach (DataColumn myDataColumn in myDataTable.Columns) {
Console.WriteLine(myDataColumn + "= " + myDataRow[myDataColumn]);
}
}
}
}

Get Return parameter from store procedure in csharp

SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText =
"EXECUTE @MyProductID = AddProduct3 @MyProductName, " +
"@MySupplierID, @MyCategoryID, @MyQuantityPerUnit, " +
"@MyUnitPrice, @MyUnitsInStock, @MyUnitsOnOrder, " +
"@MyReorderLevel, @MyDiscontinued";

mySqlCommand.Parameters.Add("@MyProductID", SqlDbType.Int);
mySqlCommand.Parameters["@MyProductID"].Direction = ParameterDirection.Output;
mySqlCommand.Parameters.Add("@MyProductName", SqlDbType.NVarChar, 40).Value = "Widget";
mySqlCommand.Parameters.Add("@MySupplierID", SqlDbType.Int).Value = 1;
mySqlCommand.Parameters.Add("@MyCategoryID", SqlDbType.Int).Value = 1;
mySqlCommand.Parameters.Add("@MyQuantityPerUnit", SqlDbType.NVarChar, 20).Value = "1 per box";
mySqlCommand.Parameters.Add("@MyUnitPrice", SqlDbType.Money).Value = 5.99;
mySqlCommand.Parameters.Add("@MyUnitsInStock", SqlDbType.SmallInt).Value = 10;
mySqlCommand.Parameters.Add("@MyUnitsOnOrder", SqlDbType.SmallInt).Value = 5;
mySqlCommand.Parameters.Add("@MyReorderLevel", SqlDbType.SmallInt).Value = 5;
mySqlCommand.Parameters.Add("@MyDiscontinued", SqlDbType.Bit).Value = 1;

SqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();

while (mySqlDataReader.Read())
{
Console.WriteLine("mySqlDataReader[\" ProductName\"] = " +
mySqlDataReader["ProductName"]);
Console.WriteLine("mySqlDataReader[\" UnitPrice\"] = " +
mySqlDataReader["UnitPrice"]);
}

mySqlDataReader.Close();

Console.WriteLine("New ProductID = " + mySqlCommand.Parameters["@MyProductID"].Value);

mySqlConnection.Close();

Call the SQL Server store procedure in asp.net and csharp

SqlConnection mySqlConnection =new SqlConnection("server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;");
mySqlConnection.Open();

SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText =
"EXECUTE AddProduct @MyProductID OUTPUT, @MyProductName, " +
"@MySupplierID, @MyCategoryID, @MyQuantityPerUnit, " +
"@MyUnitPrice, @MyUnitsInStock, @MyUnitsOnOrder, " +
"@MyReorderLevel, @MyDiscontinued";

mySqlCommand.Parameters.Add("@MyProductID", SqlDbType.Int);
mySqlCommand.Parameters["@MyProductID"].Direction = ParameterDirection.Output;
mySqlCommand.Parameters.Add( "@MyProductName", SqlDbType.NVarChar, 40).Value = "Widget";
mySqlCommand.Parameters.Add( "@MySupplierID", SqlDbType.Int).Value = 1;
mySqlCommand.Parameters.Add( "@MyCategoryID", SqlDbType.Int).Value = 1;
mySqlCommand.Parameters.Add( "@MyQuantityPerUnit", SqlDbType.NVarChar, 20).Value = "1 per box";
mySqlCommand.Parameters.Add( "@MyUnitPrice", SqlDbType.Money).Value = 5.99;
mySqlCommand.Parameters.Add( "@MyUnitsInStock", SqlDbType.SmallInt).Value = 10;
mySqlCommand.Parameters.Add( "@MyUnitsOnOrder", SqlDbType.SmallInt).Value = 5;
mySqlCommand.Parameters.Add( "@MyReorderLevel", SqlDbType.SmallInt).Value = 5;
mySqlCommand.Parameters.Add( "@MyDiscontinued", SqlDbType.Bit).Value = 1;

mySqlCommand.ExecuteNonQuery();

Console.WriteLine("New ProductID = " + mySqlCommand.Parameters["@MyProductID"].Value);

mySqlConnection.Close();

Call Simple Store Procedure in asp.net and CSharp

SqlConnection cnnUserMan;
SqlCommand cmmUser;
object objNumUsers;

// Instantiate and open the connection
cnnUserMan = new SqlConnection("server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI");
cnnUserMan.Open();

// Instantiate and initialize command
cmmUser = new SqlCommand("SimpleStoredProcedure", cnnUserMan);
cmmUser.CommandType = CommandType.StoredProcedure;

objNumUsers = cmmUser.ExecuteScalar();
Console.WriteLine(objNumUsers.ToString());

Populate a DataSet object using a store procedure in csharp

SqlConnection mySqlConnection =new SqlConnection("server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;");

SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText = "EXECUTE CustOrderHist @CustomerID";
mySqlCommand.Parameters.Add("@CustomerID", SqlDbType.NVarChar, 5).Value = "ALFKI";

SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
mySqlDataAdapter.SelectCommand = mySqlCommand;
DataSet myDataSet = new DataSet();
mySqlConnection.Open();
Console.WriteLine("Retrieving rows from the CustOrderHist() Procedure");
int numberOfRows = mySqlDataAdapter.Fill(myDataSet, "CustOrderHist");
Console.WriteLine("numberOfRows = " + numberOfRows);
mySqlConnection.Close();

DataTable myDataTable = myDataSet.Tables["CustOrderHist"];
foreach (DataRow myDataRow in myDataTable.Rows)
{
Console.WriteLine("ProductName = " + myDataRow["ProductName"]);
Console.WriteLine("Total = " + myDataRow["Total"]);
}

Add parameters to SqlCommand to call stored procedure

SqlConnection mySqlConnection = new SqlConnection("server=localhost;database=Northwind;uid=sa;pwd=sa");
mySqlConnection.Open();
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText =
"EXECUTE @MyProductID = AddProduct @MyProductName, " +
"@MySupplierID, @MyCategoryID, @MyQuantityPerUnit, " +
"@MyUnitPrice, @MyUnitsInStock, @MyUnitsOnOrder, " +
"@MyReorderLevel, @MyDiscontinued";

mySqlCommand.Parameters.Add("@MyProductID", SqlDbType.Int);
mySqlCommand.Parameters["@MyProductID"].Direction = ParameterDirection.Output;
mySqlCommand.Parameters.Add("@MyProductName", SqlDbType.NVarChar, 40).Value = "Widget";
mySqlCommand.Parameters.Add("@MySupplierID", SqlDbType.Int).Value = 1;
mySqlCommand.Parameters.Add("@MyCategoryID", SqlDbType.Int).Value = 1;
mySqlCommand.Parameters.Add("@MyQuantityPerUnit", SqlDbType.NVarChar, 20).Value = "1 per box";
mySqlCommand.Parameters.Add("@MyUnitPrice", SqlDbType.Money).Value = 5.99;
mySqlCommand.Parameters.Add("@MyUnitsInStock", SqlDbType.SmallInt).Value = 10;
mySqlCommand.Parameters.Add("@MyUnitsOnOrder", SqlDbType.SmallInt).Value = 5;
mySqlCommand.Parameters.Add("@MyReorderLevel", SqlDbType.SmallInt).Value = 5;
mySqlCommand.Parameters.Add("@MyDiscontinued", SqlDbType.Bit).Value = 1;

SqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();
while (mySqlDataReader.Read()) {
Console.WriteLine("mySqlDataReader[\" ProductName\"] = " + mySqlDataReader["ProductName"]);
Console.WriteLine("mySqlDataReader[\" UnitPrice\"] = " + mySqlDataReader["UnitPrice"]);
}
mySqlDataReader.Close();
Console.WriteLine("New ProductID = " + mySqlCommand.Parameters["@MyProductID"].Value);

mySqlConnection.Close();

Retriving URL, UserHostAddress,CurrentExecutionFilePath , PhysicalApplicationPath, RequestType


//Response.Write(Request.UserHostAddress + "
" + Request.UserHostName+ "
" + Request.UrlReferrer+ "
" + Request.Url+ "
" + Request.RequestType+ "
" + Request.RawUrl+ "
" + Request.PhysicalPath+ "
" + Request.PhysicalApplicationPath+ "
" + Request.Path+ "
" + Request.IsLocal+ "
" + Request.FilePath+ "
" + Request.CurrentExecutionFilePath+ "
" + Request.Browser+ "
" + Request.AppRelativeCurrentExecutionFilePath+ "
" + Request.ApplicationPath);
Response.Write("Request.UserHostAddress =====>"+Request.UserHostAddress+ "
" );
Response.Write("Request.UserHostName =====>" + Request.UserHostName + "
");
Response.Write("Request.UrlReferrer =====>" + Request.UrlReferrer + "
");
Response.Write("Request.Url =====>" + Request.Url + "
");
Response.Write("Request.RequestType =====>" + Request.RequestType + "
");
Response.Write("Request.RawUrl =====>" + Request.RawUrl + "
");
Response.Write("Request.PhysicalPath =====>" + Request.PhysicalPath + "
");
Response.Write("Request.PhysicalApplicationPath =====>" + Request.PhysicalApplicationPath + "
");
Response.Write("Request.Path =====>" + Request.Path + "
");
Response.Write("Request.IsLocal =====>" + Request.IsLocal + "
");
Response.Write("Request.FilePath =====>" + Request.FilePath + "
");
Response.Write("Request.CurrentExecutionFilePath =====>" + Request.CurrentExecutionFilePath + "
");
Response.Write("Request.Browser =====>" + Request.Browser + "
");
Response.Write("Request.AppRelativeCurrentExecutionFilePath =====>" + Request.AppRelativeCurrentExecutionFilePath + "
");
Response.Write("Request.ApplicationPath =====>" + Request.ApplicationPath + "
");
Response.Write("Request.AnonymousID =====>" + Request.AnonymousID + "
");
Response.Write("Request.AcceptTypes ====>" + Request.AcceptTypes);

Reading XML file into dataset in asp.net and Csharp

DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("~/xmlFiles/Employees.xml"));
dgEmployees.DataSource = ds.Tables[0].DefaultView;
dgEmployees.DataBind();

Monday, August 17, 2009

Gridview row_editing, row_deleting, row_updating and row_command events






public partial class doctors : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["hmsCon"]);

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gvDataBind();
}
}

public void gvDataBind()
{
con.Open();
string selQuery = "select * from doctorsDetails order by DNO";
SqlDataAdapter da = new SqlDataAdapter(selQuery, con);
DataSet ds = new DataSet();
da.Fill(ds);
ViewState["ds"] = ds;
con.Close();
gvDoctorDetails.DataSource = ds;
gvDoctorDetails.DataBind();
}



This is for gridview RowEditing event

protected void gvDoctorDetails_RowEditing(object sender, GridViewEditEventArgs e)
{
gvDoctorDetails.EditIndex = e.NewEditIndex;
gvDataBind();
}



This is user Interface


This is for gridview row updating event

protected void gvDoctorDetails_RowUpdating(object sender,GridViewUpdateEventArgs e)
{

int dno = Convert.ToInt32(gvDoctorDetails.DataKeys[e.RowIndex].Values[0].ToString());

TextBox txtDoctor = (TextBox)gvDoctorDetails.Rows[e.RowIndex].FindControl("txtDoctorName");
DropDownList ddlSpecialization = (DropDownList)gvDoctorDetails.Rows[e.RowIndex].FindControl("ddlSpecialization");
TextBox txtPnoneNumber = (TextBox)gvDoctorDetails.Rows[e.RowIndex].FindControl("txtDoctorPhoneNumber");
TextBox txtAddress = (TextBox)gvDoctorDetails.Rows[e.RowIndex].FindControl("txtAddress");
DropDownList ddlAvailability = (DropDownList)gvDoctorDetails.Rows[e.RowIndex].FindControl("ddlAvailability");

string doctorName = txtDoctor.Text;
string specialization = ddlSpecialization.SelectedValue;
string phoneNumber = txtPnoneNumber.Text;
string address = txtAddress.Text;
string availability = ddlAvailability.SelectedValue;

string updQuery = "update DoctorsDetails set doctorName='" + doctorName + "',specialization='" + specialization + "',doctorPhoneNumber='" + phoneNumber + "',address='" + address + "',availabilityDays='" + availability + "' where DNO=" + dno;
con.Open();
SqlCommand cmd = new SqlCommand(updQuery, con);
cmd.ExecuteNonQuery();
con.Close();
gvDoctorDetails.EditIndex = -1;
gvDataBind();
}

This is for gridview Row deleting event

protected void gvDoctorDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int dno = Convert.ToInt32(gvDoctorDetails.DataKeys[e.RowIndex].Values[0].ToString());
con.Open();
string delQuery = "delete from DoctorsDetails where DNO=" + dno;
SqlCommand cmd = new SqlCommand(delQuery, con);
cmd.ExecuteNonQuery();
con.Close();
gvDataBind();
}

This is for gridview row deleting events

protected void gvDoctorDetails_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvDoctorDetails.EditIndex = -1;
gvDataBind();
}

This is for gridview page index changing event

protected void gvDoctorDetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvDoctorDetails.PageIndex = e.NewPageIndex;
gvDataBind();
}



This is for gridview Row command event

protected void gvDoctorDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
con.Open();
if (e.CommandName.Equals("AddNewDoctor"))
{
TextBox txtNewDoctorName = (TextBox)gvDoctorDetails.FooterRow.FindControl("txtNewDoctorName");
DropDownList ddlNewSpecialization = (DropDownList)gvDoctorDetails.FooterRow.FindControl("ddlNewSpecialization");
TextBox txtNewDoctorPhoneNumber = (TextBox)gvDoctorDetails.FooterRow.FindControl("txtNewDoctorPhoneNumber");
TextBox txtNewAddress = (TextBox)gvDoctorDetails.FooterRow.FindControl("txtNewAddress");
DropDownList ddlNewAvailability = (DropDownList)gvDoctorDetails.FooterRow.FindControl("ddlNewAvailability");

string insertDoctorDetails = "insert into DoctorsDetails(doctorName,specialization,doctorPhoneNumber,address,availabilityDays) values ('" + txtNewDoctorName.Text.Trim();
insertDoctorDetails += "','" + ddlNewSpecialization.SelectedValue + "','" + txtNewDoctorPhoneNumber.Text.Trim() + "','" + txtNewAddress.Text.Trim() + "','" + ddlNewAvailability.SelectedValue + "')";

SqlCommand cmd = new SqlCommand(insertDoctorDetails, con);
cmd.ExecuteNonQuery();
con.Close();
gvDataBind();

}

}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}
}

Binging value to textbox of gridview in asp.net and csharp

In item template you can just bind and in edit item template you can bind to textbox control as well