Monday, September 22, 2008

Coding for Accessing Database File USing Code file with DataTable

Note:Place below code in App Folder



using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
///
/// Summary description for Class1
///

public class Class1
{
SqlConnection myconn;
string name,name_copy,ss;
string myConnstr;

public void sql_connection()
{

}
public Class1()
{

}

public DataTable execQuery(string myVarSQL)
{
// added SqlCommand Object 2004-02-02 to control command timeout;
SqlConnection myConn = new SqlConnection("Data Source=.;Initial Catalog=ctsi_web;Integrated Security=True");
myConn.Open();
SqlCommand myCmd = new SqlCommand(myVarSQL, myConn);
//myCmd.CommandTimeout = myCmdTimeout;
myCmd.CommandType = CommandType.Text;
SqlDataAdapter myDA = new SqlDataAdapter(myCmd);


DataTable myDT = new DataTable();
myDA.Fill(myDT);
myConn.Close();
return myDT;
}

}

Code For Filename.aspx.cs file



using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class Default2 : System.Web.UI.Page
{
Class1 global_declaration = new Class1();
DataTable dt = new DataTable();//creating new Table
protected void Page_Load(object sender, EventArgs e)
{
dt = global_declaration.execQuery("exec sample");//"sample" is a store procedure
foreach(DataRow dr in dt.Rows)//copying all data in datatable and acess from that datatable for Time Consuming
{
string name = dr["Menu_Index"].ToString();
Response.Write("THE VALUES ARE :" + name.ToString());
}

}
}

No comments: