I have a two dimensional array with 3 columns and 2 rows. I also have a database table with 3 columns. I want to insert the 2D array directly into the database.
Is there any way to that?
Any help is appreciated. I can supply more details if needed.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace _2DArrayIntoDatabaseTest
{
public partial class Form1 : Form
{
string[,] LoginInfo = new string[2, 3]{{"1", "Admin", "123"},{"2", "Admin2", "456"}};
string query;
SqlCommand Sqlcmd;
SqlConnection conn = new SqlConnection(#"Data Source=MIRAZ-PC\SQLEXPRESS;
Initial Catalog=2DArrayIntoDatabaseTest;
Integrated Security=True");
DataTable dbdataset;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.tTableAdapter.Fill(this._2DArrayIntoDatabaseTestDataSet.t);
}
int i = 0, j = 0;
private void button1_Click(object sender, EventArgs e)
{
try
{
for (i = 0; i < 2; i++)
{
for (j = 0; j < 3;j++ )
query = "INSERT INTO t(SerialNumber,UserName,Password)
values( '" + LoginInfo[i, 0] + "','"
+ LoginInfo[i, 1] + "','"
+ LoginInfo[i, 2] + "')";
}
Sqlcmd = new SqlCommand(query, conn);
conn.Open();
Sqlcmd.ExecuteNonQuery();
conn.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
try
{
query = "SELECT * from t";
Sqlcmd = new SqlCommand(query, conn);
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = Sqlcmd;
dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dbdataset;
dataGridView1.DataSource = bSource;
sda.Update(dbdataset);
//dataGridView1.Columns.Remove("rownum");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
}
}
Now this piece of code compiles fine. But in Data Grid View I can only see 1 row instead of 2.
How to solve that?
Note: Here I am trying to use a nested loop to create a dynamic query to insert a row of data one at a time.
Instead of [i, 1], [i, 2], and [i, 3] you need [i, 0], [i, 1], and [i, 2]. Also, ExecuteNonQuery() needs to happen inside the for loop.
While I'm here, I'll also show some better practice on including data in with the SQL query. The current code is crazy-vulnerable to sql injection.
private void button1_Click(object sender, EventArgs e)
{
string query = "INSERT INTO t(SerialNumber,UserName,Password) VALUES (#serial, #user, #pass);";
var dbdataset = new DataTable();
//ADO.Net does better if you create new objects, rather than try to re-use them through a class or application.
// The "using" blocks will make sure things are closed and disposed properly, even if an exception is thrown
using (var conn = new SqlConnection(#"Data Source=MIRAZ-PC\SQLEXPRESS;Initial Catalog=2DArrayIntoDatabaseTest;Integrated Security=True"))
using (var cmd = new SqlCommand(query, conn))
{
//I had to guess at column types and lengths here.
// You should use actual column types and lengths from the DB
cmd.Parameters.Add("#serial", SqlDbType.NVarChar, 20);
cmd.Parameters.Add("#user", SqlDbType.NVarChar, 20);
cmd.Parameters.Add("#pass", SqlDbType.NVarChar, 20);
conn.Open();
for (i = 0; i < LoginInfo.GetUpperBound(0); i++)
{
cmd.Parameters["#serial"].Value = LoginInfo[i, 0];
cmd.Parameters["#user"].Value = LoginInfo[i, 1];
cmd.Parameters["#pass"].Value = LoginInfo[i, 2];
try
{
//don't forget to do this INSIDE the loop
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
cmd.CommandText = "SELECT * FROM t";
var sda = new SqlDataAdapter(cmd);
try
{
sda.Fill(dbdataset);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
dataGridView1.DataSource = dbdataset;
}
Last of all... plain-text passwords like this are NOT GOOD.
Here's an example using a List<UserLoginInfo>. Note moving code to the new DB class here is not required for the List to work; it's just good practice to do that anyway.
public class UserLoginInfo
{
public string SerialNumber {get;set;} //you might want an int here instead
public string Username {get;set;}
public string Password {get;set;}
}
public static class DB
{
private static readonly string ConnectionString = #"Data Source=MIRAZ-PC\SQLEXPRESS;Initial Catalog=2DArrayIntoDatabaseTest;Integrated Security=True";
public static void SaveUserData(IEnumerable<UserLoginInfo> users)
{
string query = "INSERT INTO t(SerialNumber,UserName,Password) VALUES (#serial, #user, #pass);";
using (var conn = new SqlConnection(ConnectionString))
using (var cmd = new SqlCommand(query, conn))
{
cmd.Parameters.Add("#serial", SqlDbType.NVarChar, 20);
cmd.Parameters.Add("#user", SqlDbType.NVarChar, 20);
cmd.Parameters.Add("#pass", SqlDbType.NVarChar, 20);
conn.Open();
foreach(var user in users)
{
cmd.Parameters["#serial"].Value = user.SerialNumber;
cmd.Parameters["#user"].Value = user.UserName;
cmd.Parameters["#pass"].Value = user.Password;
cmd.ExecuteNonQuery();
}
}
}
public static DataTable GetLoginData()
{
var result = new DataTable();
using (var conn = new SqlConnection(ConnectionString))
using (var cmd = new SqlCommand("SELECT * FROM t", conn))
using (var sda = new SqlDataAdapter(cmd))
{
sda.Fill(result);
}
return result;
}
}
public partial class Form1 : Form
{
private List<UserLoginInfo> LoginInfo = new List<UserLoginInfo> {
new UserLoginInfo() {SerialNumber = "1", Username = "Admin", Password = "123"},
new UserLoginInfo() {SerialNumber = "2", UserName = "Admin2", Password = "456"}
};
private void button1_Click(object sender, EventArgs e)
{
try
{
DB.SaveUserData(LoginInfo);
dataGridView1.DataSource = DB.GetLoginData();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
Yes that can be done very easily. I have done this in vb.net as under.. I have taken array arr with 4 columns and two rows..
Dim Arr()() = {({1, "Document Title", "TITLE", "C"}),
({2, "Company Header1", "HEADER1", "C"})}
Now for inserting this into database you can simply run insert query for inserting data in your own way... for e.g.
for each item in arr.items
exexuteNonQuery("INSERT INTO Supplier (SupplierID, Name, abc,xyz) VALUES (#SID, #Name, #abc, #xyz)")
next
Related
I ask these question coz i really don't know how i'm gonna do that and is it possible to do that?
What i want is to update/change here for example STA-100418-100 in database values, update/change the 100 based on the user input, like 50 it will be STA-100418-50.
Here's the provided image to be more precise
As you can see on the image, there's a red line, if user update the quantity as 60, In Codeitem STA-100418-100 should be STA-100418-60
I really have no idea on how to do that. I hope someone would be able to help me
here's my code for updating the quantity
private void btn_ok_Click(object sender, EventArgs e)
{
using (var con = SQLConnection.GetConnection())
{
using (var selects = new SqlCommand("Update Product_Details set quantity = quantity - #Quantity where ProductID= #ProductID", con))
{
selects.Parameters.Add("#ProductID", SqlDbType.VarChar).Value = _view.txt_productid.Text;
selects.Parameters.Add("#Quantity", SqlDbType.Int).Value = Quantity;
selects.ExecuteNonQuery();
}
}
}
Here's the code to get that format in codeitems
string date = DateTime.Now.ToString("MMMM-dd-yyyy");
string shortdate = DateTime.Now.ToString("-MMddy-");
private void Quantity_TextChanged(object sender, EventArgs e)
{
Code.Text = Supplier.Text.Substring(0, 3) + shortdate + Quantity.Text;
}
Here's what I use to update SQL-Server
public static DataTable GetSqlTable(string sqlSelect)
{
string conStr = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
DataTable table = new DataTable();
SqlConnection connection = new SqlConnection(conStr);
try
{
connection.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
if (connection.State != ConnectionState.Open)
{
return table;
}
SqlCommand cmd = new SqlCommand(sqlSelect, connection);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
try
{
adapter.Fill(table);
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
throw;
}
connection.Close();
connection.Dispose();
return table;
}
public static void GetSqlNonQuery(string sqlSelect)
{
string newObject = string.Empty;
string strConn = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
SqlConnection connection = new SqlConnection(strConn);
connection.Open();
if (connection.State != ConnectionState.Open)
{
return;
}
try
{
SqlCommand cmd = new SqlCommand(sqlSelect, connection);
cmd.ExecuteNonQuery();
connection.Close();
connection.Dispose();
}
catch (Exception ex)
{
string x = ex.Message + ex.StackTrace;
throw;
}
}
Here's how to use it
DataTable dt = GetSqlTable("select Quantity from product where CodeItem = 'STA-100418-100'");
string strQuantity = dt.Rows[0]["Quantity"].ToString();
GetSqlNonQuery(string.Format("UPDATE product SET CodeItem = '{0}' WHERE = 'STA-100418-100'", strQuantity));
User will input everytime in the Quantity textbox, the textchanged event of Quantity will be hit and you will get new value everytime with the same date but with different quantity. So you can use the Code.Text to update the CodeDateTime value or you can use a global variable instead of Code.Text and use it to update the column.
string date = DateTime.Now.ToString("MMMM-dd-yyyy");
string shortdate = DateTime.Now.ToString("-MMddy-");
private void Quantity_TextChanged(object sender, EventArgs e)
{
Code.Text = Supplier.Text.Substring(0, 3) + shortdate + Quantity.Text;
}
using (var con = SQLConnection.GetConnection())
{
using (var selects = new SqlCommand("Update Product_Details set quantity = quantity - #Quantity, CodeItem = #Code where ProductID= #ProductID", con))
{
selects.Parameters.Add("#ProductID", SqlDbType.VarChar).Value = _view.txt_productid.Text;
selects.Parameters.Add("#Quantity", SqlDbType.Int).Value = Quantity;
selects.Parameters.Add("#Code", Code.Text);
}
}
as I understand it you need MSSQL String Functions
SELECT rtrim(left(Codeitem,charindex('-', Codeitem))) + ltrim(str(Quantity)) FROM ...
For detailed information
Using MySql, Substring the code item and then concatenate the quantity.
UPDATE Product_Details SET quantity = #quantity,CodeIem = CONCAT(SUBSTR(#code,1,11),#quantity) WHERE ProductID= #ProductID
I have two forms with name Sale and Sale return
sale form is working fine, but I have an issue with sale return form.
I want to get all rows in datagridview from Sale Database with for loop, but when I run given below select query, only one row has select.
So please help me for resolve the this issue.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace DataGridViewtoTextbox
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
Random rand = new Random();
DataGridView dgv = this.dataGridView1;
//DATAGRIDVIEW SETTING
dgv.AllowUserToAddRows = false;
dgv.RowHeadersVisible = false;
dgv.SelectionMode = DataGridViewSelectionMode.RowHeaderSelect;
//ADD COLUMN HEADERS
dgv.Columns.Add("Invoice", "SInvoice");
dgv.Columns.Add("Code", "ItemCode");
dgv.Columns.Add("Amount", "Price");
dgv.Columns.Add("Quantity", "Quantity");
//ADD 10 ROWS
SqlConnection con = new SqlConnection("Data Source=.; Initial Catalog=mateenwin; User ID=sa; Password=123");
con.Open();
SqlCommand cmd = new SqlCommand("Select Sale_Invoice_No,Item_Code,Item_Payable_Amount from sale where Sale_Invoice_No = '" + textBox1.Text + "'", con);
SqlDataReader sdr;
sdr = cmd.ExecuteReader();
if (sdr.Read())
{
int itm = (Int32)sdr["Sale_Invoice_No"];
int inovice = (Int32)sdr["Item_Code"];
double ptype = (double)sdr["Item_Payable_Amount"];
int qnty = (Int32)0;
////NOW, POPULATE THE DATA INTO THE CELLS
int n = dgv.Rows.Add(sdr);
for (int i = 0; i < dgv.Rows.Count; i++)
{
dataGridView1.Rows[i].Cells[0].Value = itm;
dataGridView1.Rows[i].Cells[1].Value = itm;
dataGridView1.Rows[i].Cells[2].Value = ptype;
dataGridView1.Rows[i].Cells[3].Value = qnty;
con.Close();
}
}
//int inv =Convert.ToInt32(cmd.Parameters.AddWithValue("#Sale_Invoice", "Sale_Invoice"));
//int cod=Convert.ToInt32( cmd.Parameters.AddWithValue("#Item_Code", "Item_Code"));
//double amount=Convert.ToDouble( cmd.Parameters.AddWithValue("#Item_Payable_Amount", "Item_Payable_Amount"));
//cmd.ExecuteScalar();
////NOW, POPULATE THE DATA INTO THE CELLS
//for (int i = 0; i < 10; i++)
//{
// double price = rand.Next(1, 30) * rand.NextDouble();
// dgv.Rows[i].Cells[0].Value = inv;
// dgv.Rows[i].Cells[1].Value = cod;
// dgv.Rows[i].Cells[2].Value = amount;
// dgv.Rows[i].Cells[3].Value = 0;
//}
//CLEARS THE DEFAULT SELECTION WHICH IS THE FIRST ROW
dgv.ClearSelection();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
dataGridView1.BeginEdit(true);
int cod = Convert.ToInt32(dataGridView1.CurrentRow.Cells[1].Value);
double price = Convert.ToDouble(dataGridView1.CurrentRow.Cells[2].Value);
dataGridView1.CurrentRow.Cells[3].Value =Convert.ToDouble( (cod) * (price));
}
}
}
Try the below code:
SqlConnection con = new SqlConnection("Data Source=.; Initial Catalog=mateenwin; User ID=sa; Password=123");
con.Open();
SqlCommand cmd = new SqlCommand(string.Format("Select Sale_Invoice_No as Invoice, Item_Code as Code, Item_Payable_Amount as Amount, 0.00 as Quantity from sale where Sale_Invoice_No = '{0}'", textBox1.Text), con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet dsInvoices = new DataSet();
sda.Fill(dsInvoices);
dgv.DataSource = null;
dgv.DataSource = dsInvoices.Tables.Count > 0 ? dsInvoices.Tables[0] : null;
If its not essential to insert data using a for loop you can get the data to a Dataset and bind it with the grid as follows.
private void Form2_Load(object sender, EventArgs e)
{
string txt=textBox1.Text;
DataSet ds = new DataSet();
ds=db.getDataQuery(txt);
if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
}
Query to get the data
public DataSet getDataQuery(string txt)
{
try
{
String strQuery = #"Select Sale_Invoice_No, Item_Code, Item_Payable_Amount from sale where Sale_Invoice_No = '" + txt + "'";
return SqlHelper.ExecuteDataset(your_connection_string_name, CommandType.Text, strQuery);
}
catch (Exception ex)
{
throw ex;
}
}
Please edit the answer according to yours. You have to make a connection string. Try to create connections globaly. It's good habbit.
it seems you are closing connection to database inside for loop.so it is expected that after processing first row connection will be closed.
Also reader need to advanced for next row until it has row.
Also you need to put proper check on reader before using it.
Please check my code here and use it.
do
{
if (sdr.HasRows)
{
int itm = (Int32)sdr["Sale_Invoice_No"];
int inovice = (Int32)sdr["Item_Code"];
double ptype = (double)sdr["Item_Payable_Amount"];
int qnty = (Int32)0;
////NOW, POPULATE THE DATA INTO THE CELLS
int n = dgv.Rows.Add(sdr);
for (int i = 0; i < dgv.Rows.Count; i++)
{
dataGridView1.Rows[i].Cells[0].Value = itm;
dataGridView1.Rows[i].Cells[1].Value = itm;
dataGridView1.Rows[i].Cells[2].Value = ptype;
dataGridView1.Rows[i].Cells[3].Value = qnty;
}
}
} while (sdr.NextResult());
con.Close();
I can not get any row data from database using c# asp.net.I am trying to fetch one row data from my DB but it is not returning any row.I am using 3-tire architecture for this and i am explaining my code below.
index.aspx.cs:
protected void userLogin_Click(object sender, EventArgs e)
{
if (loginemail.Text.Trim().Length > 0 && loginpass.Text.Trim().Length >= 6)
{
objUserBO.email_id = loginemail.Text.Trim();
objUserBO.password = loginpass.Text.Trim();
DataTable dt= objUserBL.getUserDetails(objUserBO);
Response.Write(dt.Rows.Count);
}
}
userBL.cs:
public DataTable getUserDetails(userBO objUserBO)
{
userDL objUserDL = new userDL();
try
{
DataTable dt = objUserDL.getUserDetails(objUserBO);
return dt;
}
catch (Exception e)
{
throw e;
}
}
userDL.cs:
public DataTable getUserDetails(userBO objUserBO)
{
SqlConnection con = new SqlConnection(CmVar.convar);
try
{
con.Open();
DataTable dt = new DataTable();
string sql = "SELECT * from T_User_Master WHERE User_Email_ID= ' " + objUserBO.email_id + "'";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter objadp = new SqlDataAdapter(cmd);
objadp.Fill(dt);
con.Close();
return dt;
}
catch(Exception e)
{
throw e;
}
}
When i am checking the output of Response.Write(dt.Rows.Count);,it is showing 0.So please help me to resolve this issue.
It looks like your your query string has a redundant space between ' and " mark. That might be causing all the trouble as your email gets space in front.
It is by all means better to add parameters to your query with use of SqlConnection.Parameters property.
string sql = "SELECT * from T_User_Master WHERE User_Email_ID=#userID";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#userID", SqlDbType.NVarChar);
cmd.Parameters["#userID"].Value = objUserBO.email_id;
I need some help to complete this. I have searched and tried several ways but is not enetring in my head yet. It is not homework! I am a self learner.
I managed to populate a grid selecting the table from a dropdown:
private void radDropDownList1_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e)
{
if (radDropDownList1.SelectedIndex > 0)
{
radGridView1.Visible = true;
label8.Text = radDropDownList1.SelectedValue.ToString();
DataTable dt = new DataTable();
var selectedTable = radDropDownList1.SelectedValue; //Pass in the table name
string query = #"SELECT * FROM " + selectedTable;
using (var cn = new SqlConnection(connString))
{
cn.Open();
try
{
SqlCommand cmd = new SqlCommand(query, cn);
using (var da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
catch (SqlException ex)
{
//MessageBox.Show(ex.StackTrace);
}
}
radGridView1.DataSource = dt;
}
Now I am trying to write the event to update the sql table using the grid as datasource:
private void radGridView1_CellEndEdit(object sender, Telerik.WinControls.UI.GridViewCellEventArgs e)
{
DataTable dt = (DataTable)radGridView1.DataSource;
DataSet ds = new DataSet();
ds.Tables[0] = dt;
try
{
//**I am lost here!**
}
catch
{
}
}
Could you please help? How can I now update the sql table?
I don't really like the way you are managing the updates but... this code here will send an update statement:
using (var cn = new SqlConnection(connString))
{
cn.Open();
try
{
SqlCommand cmd = new SqlCommand("UPDATE YourTable SET Column = #Parm1 WHERE Col = #Parm2", cn);
var parm1 = cmd.CreateParameter("Parm1");
parm1.Value = "SomeValue";
var parm2 = cmd.CreateParameter("Parm2");
parm2.Value = "SomeOtherValue";
cmd.Parameters.Add(parm1);
cmd.Parameters.Add(parm2);
int rowsAffected = cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
//MessageBox.Show(ex.StackTrace);
}
}
Im new to using ASP.NET and would like to know how I can select a random row from a sql database and then display the fields in a html table on a separate page. It is intended that the user can press on button which will retrieve a random movie from the database and then display the movie details in a html table on a new page. I am not sure how to go about this and have been trying to use labels to display the data. Here is a sample of the code so far:
private SqlConnection conn;
protected void Page_Load(object sender, EventArgs e)
{
ConnectionStringSettings connString = ConfigurationManager.ConnectionStrings ["MovieAppConnectionString1"];
conn = new SqlConnection(connString.ConnectionString);
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
try
{
conn.Open();
string queryString = "SELECT TOP 1 * FROM Movie ORDER BY NEWID()";
SqlCommand cmd = new SqlCommand(queryString, conn);
{
SqlDataReader reader = cmd.ExecuteReader();
StringBuilder MyStringBuilder = new StringBuilder();
while (reader.Read())
{
Image2.Text = reader[2].ToString();
Label1.Text = reader[1].ToString();
Desc.Text = reader[3].ToString();
Direc.Text = reader[5].ToString();
Strs.Text = reader[7].ToString();
Rtime.Text = reader[4].ToString();
ImdbRt.Text = reader[8].ToString();
}
}
}
finally
{
conn.Close();
}
Server.Transfer("MovieSelected.aspx");
Change your sql server query from :
SELECT TOP 1 * FROM Movie ORDER BY NEWID()
to
SELECT TOP 1 * FROM Movie ORDER BY RAND()
In your aspx.cs file:
int iLength = 0;
int index = 0;
DataTable dt = new DataTable();
dt = SqlComm.SqlDataTable("SELECT * FROM Movie");
object obj = new object();
obj = SqlComm.SqlReturn("SELECT COUNT (yourTargetColumn) FROM yourTable");
if (obj != null)
iLength = Convert.ToInt32(obj);
string[] stringArray = new string[iLength];
for (index = 0; index < iLength; index++)
{
stringArray[index] = (string)dt.Rows[index]["yourTargetColumn"];
}
foreach (string strArray in stringArray)
{
Label yourLabel = new Label();
PH.Controls.Add(yourLabel);
}
In your .aspx file:
<asp:PlaceHolder ID="PH" runat="server"></asp:PlaceHolder>
Add a class to your App_Code folder named "SqlComm.cs":
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
public class SqlComm
{
static string DatabaseConnectionString = "your connection string";
public static object SqlReturn(string sql)
{
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
object result = (object)cmd.ExecuteScalar();
return result;
}
}
public static DataTable SqlDataTable(string sql)
{
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Connection.Open();
DataTable TempTable = new DataTable();
TempTable.Load(cmd.ExecuteReader());
return TempTable;
}
}
Note: Do not forget to add the using System.Data.SqlClient to your code. Also, you just have to customize the SELECT command in order to get the data you want.