You must Sign In to post a response.

Sql query into Datatable in C#

HI frinde


I have a table called CM in SQL 2008

I want to write a query to select all teh columns and taking them into DataTable.

I have like this

String Connection = ConfigurationManager.ConnectionStrings["GridConnectionString"].ToString();
SqlConnection con = new SqlConnection(Connection);







DataTable DtGridDLL;
StringBuilder sbSQL = new StringBuilder();


return DtGridDLL;






Please sugegst me



thaanks a lot


Comments

Author: Paritosh Mohapatra28 Apr 2011 Member Level: Gold   Points : 4

Please check the following code:


protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = GetColumns("select * from tbl1");
}

public DataTable GetColumns(string query)
{
String Connection = ConfigurationManager.ConnectionStrings["GridConnectionString"].ToString();
SqlConnection con = new SqlConnection(Connection);
DataTable DtGridDLL = new DataTable();
SqlDataAdapter sqlda = new SqlDataAdapter(query, con);
sqlda.Fill(DtGridDLL);
return DtGridDLL;
}

Author: Anil Kumar Pandey28 Apr 2011 Member Level: Diamond   Points : 4

You can also use a Data set as the data set store the details in table format.



public DataSet GetValue(string query)
{
String Connection = ConfigurationManager.ConnectionStrings["GridConnectionString"].ToString();
SqlConnection con = new SqlConnection(Connection);
Dataset ds = new DataSet();
SqlDataAdapter sqlda = new SqlDataAdapter(query, con);
sqlda.Fill(ds);
return ds;
}



now you can access the tables like.


string a = ds.Tables[0].Rows[0][0].ToString();
string b = ds.Tables[1].Rows[0][0].ToString();

Author: Ravindran28 Apr 2011 Member Level: Diamond   Points : 4

Simply you can get value of table like this way


using System.Data;
using System.Data.SqlClient;

public partial class GridViewOperation : System.Web.UI.Page
{
SqlConnection sqlcon = new SqlConnection(@"Server= RAVI\SQLEXPRESS;database=test;uid=xxxx;pwd=yyyy;"); //Change your connection string value
SqlCommand sqlcmd;
SqlDataAdapter da;
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridData();
}
}
void GridData()
{
sqlcmd = new SqlCommand("select * from emp", sqlcon);
sqlcon.Open();
da = new SqlDataAdapter(sqlcmd);
dt.Clear();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
else
{
Label1.Text = "No Recods Found";
}
}
}

Author: sugandha28 Apr 2011 Member Level: Gold   Points : 4


protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Server= dell;database=DB;uid=sa;pwd=sa;"
SqlCommand cmd = new SqlCommand("select * from Employee", sqlcon);
con.Open();
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adpt.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
else
{
Lbl_msg.Text = "No Data Found";
}
}
}