How do I make a query to retrieve specific data - c#

I am learning C# and SQL Server. I was following a simple tutorial, which led me to the creation of a class DBconnection that connects and updates the DB. Then I have a simple C# form that navigates back and forth on table rows using a button and a DataSet to clone the data, and then displays the info on some labels.
No problem 'till here, but then I thought, what if I wanted to display a single value(column) of a specific row, say "show me the last name of the person with a certain first name".
I'm familiar with the SQL query commands, so what I want is something like this:
SELECT last_name FROM Employees WHERE first_name = 'Jason'
Follows my code...
DBconnection.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace cemiGEST
{
/// <summary>
/// A class that makes the connection to the SQL Database
/// </summary>
class DBconnection
{
// variables
private string sql_string;
private string strCon;
System.Data.SqlClient.SqlDataAdapter da_1;
// set methods
public string Sql
{
set { sql_string = value; }
}
public string connection_string
{
set { strCon = value; }
}
// DataSet
public System.Data.DataSet GetConnection
{
get { return MyDataSet(); }
}
// MyDataSet method
private System.Data.DataSet MyDataSet()
{
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(strCon);
con.Open();
da_1 = new System.Data.SqlClient.SqlDataAdapter(sql_string, con);
System.Data.DataSet dat_set = new System.Data.DataSet();
da_1.Fill(dat_set, "Table_Data_1");
con.Close();
return dat_set;
}
// Update DB method
public void UpdateDB(System.Data.DataSet ds)
{
System.Data.SqlClient.SqlCommandBuilder cb = new System.Data.SqlClient.SqlCommandBuilder(da_1);
cb.DataAdapter.Update(ds.Tables[0]);
}
}
}
I am accessing the values (when moving back and forth) by just incrementing by one a variable that updates the row number. Some exemplifying code follows.
public partial class Example : Form
{
// variables
DBconnection objConnect;
string conStringAUTH;
DataSet ds;
DataRow dr;
int maxRows;
int inc = 0;
private void Login_Load(object sender, EventArgs e)
{
CloseBeforeLogin = true;
try
{
objConnect = new DBconnection();
conStringAUTH = Properties.Settings.Default.authConnectionString;
objConnect.connection_string = conStringAUTH;
objConnect.Sql = Properties.Settings.Default.authSQL;
ds = objConnect.GetConnection;
maxRows = ds.Tables[0].Rows.Count;
if (maxRows == 0)
{
MessageBox.Show("No user found. Loading first run wizard.");
NewUser newUser = new NewUser();
newUser.ShowDialog();
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
}
I'm sure this is simple, but I'm not getting there.
EDIT:
I would prefer using my class DBconnection and without external libraries. I'm not at the PC with the project, so can't test anything right now, but after a good night of sleep over the matter, and after (re)looking at my code, I may have found the answer. Please tell me if you think this would do the trick:
In my second class (where I connect to and access the DB), I have already using a SQL query, more specifically here:
objConnect.Sql = Properties.Settings.Default.authSQL;
This query (authSQL), was created by me and embedded on the Settings, and here I am importing it. So, if I do the following instead, do you think it would work:
objConnect.Sql = "SELECT last_name FROM Employees WHERE first_name = 'Jason'";
The "Properties.Settings.Default.authSQL" code is nothing more than a shortcut to a string "SELECT * FROM AUTH" - AUTH is my table, which I called Employees for the sake of simplicity.
So, it would be something like this:
public partial class Example : Form
{
// variables
DBconnection objConnect;
string conStringAUTH;
DataSet ds;
DataRow dr;
int maxRows;
int inc = 0;
private void Login_Load(object sender, EventArgs e)
{
CloseBeforeLogin = true;
try
{
objConnect = new DBconnection();
conStringAUTH = Properties.Settings.Default.authConnectionString;
objConnect.connection_string = conStringAUTH;
objConnect.Sql = "SELECT last_name FROM Employees WHERE first_name = 'Jason'";
ds = objConnect.GetConnection;
// Data manipulation here
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}

There's no need for a dataset here. If you know the sql you want: use it - perhaps with some parameterization. For example, using "dapper", we can do:
string firstName = "Jason";
var lastNames = con.Query<string>(
"SELECT last_name FROM Employees WHERE first_name = #firstName",
new { firstName }).ToList();

Check this ....hope this also works...
//String Declaration
string Sqlstr = "select CountryCode,Description,Nationality from ca_countryMaster where isDeleted=0 and CountryCode = 'CAN' ";
string DBCon = "Data Source=RAJA;Initial Catalog=CareHMS;Integrated Security=True;";
SqlConnection SqlCon = new SqlConnection(DBCon);
SqlDataAdapter Sqlda;
DataSet ds = new DataSet();
try
{
SqlCon.Open();
Sqlda = new SqlDataAdapter(Sqlstr, SqlCon);
Sqlda.Fill(ds);
gdView.DataSource = ds.Tables[0];
gdView.DataBind();
}
catch (Exception ex)
{
lbl.text = ex.Message;
}
finally
{
ds.Dispose();
SqlCon.Close();
}

Related

Connection to SQL Server through ADO.NET - Empty Listbox

Trying to set up a connection to my local SQL Server Express instance so that I can display columns in a listbox. Th build runs fine and I can't see errors, but there is no data in the listbox. I have tested the query and that is fine. I am using NT Authentication to the database. Any ideas where I might have gone wrong?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void customers_SelectedIndexChanged(object sender, EventArgs e)
{
string commstring = "Driver ={SQL Server}; Server = DESKTOP-5T4MHHR\\SQLEXPRESS; Database = AdventureWorks2014; Trusted_Connection = Yes;";
string connstring = "SELECT FirstName, LastName FROM Person.Person";
SqlDataAdapter customerDataAdapater = new SqlDataAdapter(commstring, connstring);
DataSet customerDataSet = new DataSet();
customerDataAdapater.Fill(customerDataSet, "Person.Person");
DataTable customerDataTable = new DataTable();
customerDataTable = customerDataSet.Tables[0];
foreach (DataRow dataRow in customerDataTable.Rows)
{
customers.Items.Add(dataRow["FirstName"] + " (" + dataRow["LastName"] + ")");
}
}
}
I tested your code in a sample project here and I realized you passed the parameters to SqlDataAdapter constructor in a wrong order.
After changing the follow line:
SqlDataAdapter customerDataAdapater = new SqlDataAdapter(commstring, connstring);
by
SqlDataAdapter customerDataAdapater = new SqlDataAdapter(connstring, commstring);
the listbox was filled successfully.
Your connection string seems weird.....
Could you try using just this:
string commstring = "Server=DESKTOP-5T4MHHR\\SQLEXPRESS;Database=AdventureWorks2014;Trusted_Connection=Yes;";
Also: why are you first creating a DataSet, filling in a single set of data, and then extracting a DataTable from it?? This is unnecessarily complicated code - just use this instead:
SqlDataAdapter customerDataAdapater = new SqlDataAdapter(commstring, connstring);
// if you only ever need *one* set of data - just use a DataTable directly!
DataTable customerDataTable = new DataTable();
// Fill DataTable with the data from the query
customerDataAdapater.Fill(customerDataTable);
Update: I would really rewrite your code to something like this:
// create a separate class - call it whatever you like
public class DataProvider
{
// define a method to provide that data to you
public List<string> GetPeople()
{
// define connection string (I'd really load that from CONFIG, in real world)
string connstring = "Server=MSEDTOP;Database=AdventureWorks2014;Trusted_Connection=Yes;";
// define your query
string query = "SELECT FirstName, LastName FROM Person.Person";
// prepare a variable to hold the results
List<string> entries = new List<string>();
// put your SqlConnection and SqlCommand into "using" blocks
using (SqlConnection conn = new SqlConnection(connstring))
using (SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
// iterate over the results using a SqlDataReader
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
// get first and last name from current row of query
string firstName = rdr.GetFieldValue<string>(0);
string lastName = rdr.GetFieldValue<string>(1);
// add entry to result list
entries.Add(firstName + " " + lastName);
}
rdr.Close();
}
conn.Close();
}
// return the results
return entries;
}
}
And in your code-behind, you only need to do something like this:
protected override void OnLoad(.....)
{
if (!IsPostback)
{
List<string> people = new DataProvider().GetPeople();
customers.DataSource = people;
customers.DataBind();
}
}
but I still don't understand what you were trying to when the SelectedIndexChanged event happens.....

How do I place data from the SQL Server database into a TextBox?

I am missing something very simple. I have a form with 5 textBox and want to fill them with the data from the SQL Server database. Here is what I have so far:
As I debug this code line by line it returns to the calling block at the connection.open() line.
public void Get_Contact_Info()
{
using (DataAccessClass.sql_Connection)
{
string SQL = "SELECT * FROM Customer_Contacts WHERE Contact_ID = #contact_Id";
SqlCommand sqlCommand = new SqlCommand(SQL, DataAccessClass.sql_Connection);
sqlCommand.Parameters.AddWithValue("#Contact_Id", contact_Id);
sqlCommand.Parameters.AddWithValue("#Contact_Direct_Number", contact_Direct_NumberTextBox);
sqlCommand.Parameters.AddWithValue("#Contact_Cell_Number", contact_Cell_NumberTextBox);
sqlCommand.Parameters.AddWithValue("#Contact_Email", contact_EmailTextBox);
sqlCommand.Parameters.AddWithValue("#Contact_Department", contact_DepartmentTextBox);
DataAccessClass.sql_Connection.Open();
using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
{
while (sqlDataReader.Read())
{
contact_Id = sqlDataReader["Contact_ID"].ToString();
}
DataAccessClass.sql_Connection.Close();
}
}
}
I have been doing a pretty good job of getting info from the user and saving it to the SQL Server DataTable but know I want to get some out so that I can edit the info.
Any help will be gratefully appreciated.
Here is my DataAccessClass
public static class DataAccessClass
{
static SqlConnection sqlConnection = new SqlConnection();
public static SqlConnection sql_Connection
{
get { return sqlConnection; }
}
public static void OpenConnection()
{
string sqlString = Properties.Settings.Default.ConnectionString;
sqlConnection.ConnectionString = sqlString;
sqlConnection.Open();
}
public static void CloseConnection()
{
sqlConnection.Close();
}
}
Here is how I am calling Get_Contact_Info.
private void Customer_Add_Contact_Form_Load(object sender, EventArgs e)
{
this.customer_ContactsBindingSource.AddNew();
if (contact_Id == null)
{
contact_NameTextBox.Select();
}
else
{
Get_Contact_Info();
}
}
From a DataGridView I am selecting a row and passing customer_ID to the Customer_Add_Contact_Form so that I can edit the contact information. Here is the code for this step:
DataGridViewRow row = customer_ContactsDataGridView.CurrentCell.OwningRow;
string contact_ID = row.Cells[0].Value.ToString();
string customer_Ship_ID = null;
using (Form Customer_Add_Contact_Form = new Customer_Add_Contact_Form(customer_Ship_ID, contact_ID))
As discussed here it is better to let connection pooling manage the connections, so you can simplify your code to:
public void Get_Contact_Info()
{
using (var connection = new SqlConnection(roperties.Settings.Default.ConnectionString))
{
connection.Open();
var SQL = "SELECT * FROM Customer_Contacts WHERE Contact_ID = #contact_Id";
var sqlCommand = new SqlCommand(SQL, connection);
sqlCommand.Parameters.AddWithValue("#Contact_Id", contact_Id);
using (var sqlDataReader = sqlCommand.ExecuteReader())
{
while (sqlDataReader.Read())
{
contact_Id = sqlDataReader["Contact_ID"].ToString();
TextBoxName.Text = sqlDataReader["Contact_Name"].ToString();
//etc ...
}
}
}
}
I have removed unused parameters and created a new connection. Possibly you tried to open a connection using .Open() without initializing it with a connections string (is it roperties?)

Delete selected row from datagrid view and update mysql database in C#

m developing application for my office and in my application there is a datagrid view that linked to a mysql database. local users can update the database using datagridview but they cant delete any recodes. i want to implement a method that user's are select exact raw in the datagridview and delete it as well as delete the database record soon. i managed to make select and delete datagridview row using below code but it not update the database
private void button60_Click(object sender, EventArgs e)
{
foreach (DataGridViewCell oneCell in dataGridView1.SelectedCells)
{
if (oneCell.Selected)
dataGridView1.Rows.RemoveAt(oneCell.RowIndex);
}
}
and this is my connection string that i normally use to view the database data in datagrid view. i don't have good knowledge to combined these two.can someone please show me how to do that
my connection string
private void showdatagrid()
{
string constring = string.Format("datasource='{0}';username=******;port=3306;password=***********;Connect Timeout=20000;Command Timeout=28800", dbserverip.Text);
MySqlConnection conwaqDatabase = new MySqlConnection(constring);
MySqlCommand cmdwaqDatabase = new MySqlCommand(" select * from warit.loans ; ", conwaqDatabase);
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmdwaqDatabase;
dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bsource = new BindingSource();
bsource.DataSource = dbdataset;
dataGridView1.DataSource = bsource;
sda.Update(dbdataset);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
try this code
private void button60_Click(object sender, EventArgs e)
{
foreach (DataGridViewCell oneCell in dataGridView1.SelectedCells)
{
if (oneCell.Selected)
{
dataGridView1.Rows.RemoveAt(oneCell.RowIndex);
int loannumber = dataGridView1.Rows[oneCell.RowIndex].Cells['index of loannumber column in datagridview'].Value; // assuming loannmber is integer
string username = dataGridView1.Rows[oneCell.RowIndex].Cells['index of username column in datagridview'].Value; // assuming username is string
/* Now create an object of MySqlConnection and MySqlCommand
* and the execute following query
*/
string query = string.Format("DELETE FROM table_name WHERE loannumber = {0} AND username = '{1}'", loannumber, username);
}
}
}
string connection = "server = URL; uid = user; pwd = password; database = database;";
using (MySqlConnection conn = new MySqlConnection(connection)) {
conn.Open();
string idLocRemv = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
string removeVolCred = "DELETE FROM TableName WHERE ID = " + idLocRemv;
using (MySqlCommand command = new MySqlCommand(removeVolCred, fbcConn)) {
command.ExecuteNonQuery();
}
conn.Close();
}
Apply necessary exception handlers. (try catch finally)
Additionally, you will need to re-load DataGridView afterwards.

C# Mysql multiple queries

Im trying to build up a little status-tool. I need to get results of multiple queries (about 4-5). The general connection-setup and 'how-to-read-data' is already done but I cant figure out how the another query executed.
Everything I found while searching for it is for the SqlClient. Im totally overcharged with this.
Here is my code so far (be patient, im a newbie to this):
private void button1_Click(object sender, EventArgs e)
{
if(listView1.Items.Count > 1)
{
listView1.Items.Clear();
}
var listMember = new List<string>{};
var listOnline = new List<string>{};
// SQL PART //
string connString = "Server=10*****;Port=3306;Database=e***;Uid=e***;password=********************;";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT fullname,online FROM member WHERE active = '1' ORDER BY online DESC";
try
{
conn.Open();
}
catch (Exception ex)
{
listView1.Items.Add("Error: " + ex);
}
MySqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
listMember.Add(reader["fullname"].ToString());
listOnline.Add(reader["online"].ToString());
}
conn.Close();
// SQL ENDING //
// SET ENTRIES TO LISTVIEW //
int counter = 0;
foreach(string member in listMember)
{
ListViewItem item = new ListViewItem(new[] { member, listOnline.ElementAt(counter) });
item.ForeColor = Color.Green;
listView1.Items.Add(item);
counter++;
}
}
Im not really sure how the design/layout will look like in the end, so I would like to just append the results to lists in the sql-part to process the data later out of the lists.
Do I really have to setup a complete new connection after conn.Close()? Or is there any other way? I can just imagine: 5 queries with their own connection,try,catch and 2 loops... this will get about 100-200 lines just for getting the results out of 5 queries. Isnt that a bit too much for such an easy thing?
Hope for some help.
Greetings.
According to the new comments my latest code:
Top:
public partial class Form1 : Form
{
public static string connString = "Server=10****;Port=3306;Database=e****;Uid=e****;password=****;";
public Form1()
{
InitializeComponent();
MySqlConnection conn = new MySqlConnection(connString); // Error gone!
}
Body part:
public void QueryTwoFields(string s, List<string> S1, List<string> S2)
{
try
{
MySqlCommand cmd = conn.CreateCommand(); // ERROR: conn does not exist in the current context.
cmd.CommandType = CommandType.Text;
string command = s;
cmd.CommandText = command;
MySqlDataReader sqlreader = cmd.ExecuteReader();
while (sqlreader.Read())
{
S1.Add(sqlreader[0].ToString());
S2.Add(sqlreader[1].ToString());
}
sqlreader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
if(listView1.Items.Count > 1)
{
listView1.Items.Clear();
}
var listMember = new List<string>{};
var listOnline = new List<string>{};
using (conn) // ERROR: conn does not exist in the current context.
{
conn.Open();
///...1st Query
QueryTwoFields("SELECT fullname,online FROM member WHERE active = '1' ORDER BY online DESC",listMember,listOnline);
//...2nd query
//QueryTwoFields("your new Select Statement", otherList, otherList);
}
}
You don't have to close connection every time you execute one query rarher than close the sqlreader assigned to that connection. Finally when all of your queries have been executed you close the connection. Consider also the use of using:
You cal also define a method for execution your Query in order for your code not to be repetive:
public void QueryTwoFields(string s, List<string> S1, List<string> S2)
///Select into List S1 and List S2 from Database (2 fields)
{
try
{
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
string command = s;
cmd.CommandText = command;
MySqlDataReader sqlreader = cmd.ExecuteReader();
while (sqlreader.Read())
{
S1.Add(sqlreader[0].ToString());
S2.Add(sqlreader[1].ToString());
}
sqlreader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
if(listView1.Items.Count > 1)
{
listView1.Items.Clear();
}
var listMember = new List<string>{};
var listOnline = new List<string>{};
// SQL PART //
using (conn)
{
conn.Open();
///...1st Query
QueryTwoFields("SELECT fullname,online FROM member WHERE active = '1' ORDER BY online DESC",listmember,listonline)
//...2nd query
QueryTwoFields("your new Select Statement",myOtherList1,myOtherlist2)
....
}
}
EDIT :
Take in mind you cant define QueryTwoFields method inside button handler. You must define it outside (see code above).
Also Define your connection data in the start of the programm:
namespace MyProject
{
/// <summary>
/// Defiine your connectionstring and connection
/// </summary>
///
public partial class Form1 : Form
{ public static string connString = "Server=10*****;Port=3306;Database=e***;Uid=e***;password=********************;";
MySqlConnection conn = new MySqlConnection(connString);
.........
Datatables are fantastic
Using a data table is a nice way to do both read and write. And it comes with the luxury of eveything you can do with a datatable - like asssigning it directly to a datagrid control, sorting, selecting and deleting while disconnected.
The sample below assumes a MySqlConnection conection property managed by calls to your own OpenConnection() and CloseConnection() methods not shown.
Simple datatable read demo:
public DataTable Select(string query = "")
{
//Typical sql: "SELECT * FROM motorparameter"
DataTable dt = new DataTable();
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
dt.Load(dataReader);
//close Data Reader
dataReader.Close();
//close Connection
this.CloseConnection();
//return data table
return dt;
}
else
{
return dt;
}
}
In case of writing back the datatable to the database - supply the SQL you used in the read (or would have used to read to the data table):
public void Save(DataTable dt, string DataTableSqlSelect)
{
//Typically "SELECT * FROM motorparameter"
string query = DataTableSqlSelect;
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand mySqlCmd = new MySqlCommand(query, connection);
MySqlDataAdapter adapter = new MySqlDataAdapter(mySqlCmd);
MySqlCommandBuilder myCB = new MySqlCommandBuilder(adapter);
adapter.UpdateCommand = myCB.GetUpdateCommand();
adapter.Update(dt);
//close Connection
this.CloseConnection();
}
else
{
}
}
The neat thing the datatable is extremely flexible. You can run your own selects against the table once it contains data and before writing back you can set or reset what rows needs updating and by default the datatable keeps track of what rows you update in the table. Do not forget primary key column(s) for all tables in the db.
For multiple queries consider if possible using a join between the database tables or same table if data related or use a UNION sql syntax if column count and type of data is the same. You can allways "create" your extra column in the select to differ what data comes from what part of the UNION.
Also consider using CASE WHEN sql syntax to conditionally select data from different sources.

The ConnectionString property has not been initialized. Winforms C#.net

I am in the process of adding a new form to an already established Winforms application.
I have a DataGridView on my form and the relevant method in code behind which calls my dbAPI DataTable method. I have written the method with exactly the same code as many others used in the dbAPI class but for some reason it is not initialising the connection string...
public DataTable getMyTable()
{
//used for populating the DataGridView
SqlCommand _com = new SqlCommand(string.Format("select * from tab.myTable where Country = 'Angola' "), _conn);
_com.CommandTimeout = _command_timeout;
DataSet _ds = new DataSet();
SqlDataAdapter _adapt = new SqlDataAdapter();
try
{
_adapt.SelectCommand = _com;
int i = _adapt.Fill(_ds, "Asset_Transactions");
if (_ds.Tables.Count > 0)
{
return _ds.Tables[0];
}
else
{
return makeErrorTable("GetMyTable", "No Table Returned for myTable");
}
}
catch (Exception e)
{
return makeErrorTable("GetMyTable", e.Message);
}
}
_conn is an SQLConnection object. My connection string is in the app.config...
class dbAPI
{
Utils _utils = new Utils();
//this is the API between the Application Code and the LDB Database
string _ldb_connection_string = (string)dii.Properties.Settings.Default.connLDB; //connection string but with only one \ in settings as it gets converted to \\
int _command_timeout = Convert.ToInt32((string)dii.Properties.Settings.Default.commandTimeOut); //Command time out
SqlConnection _conn = new SqlConnection();
public dbAPI()
{
//constructor
}
#region --------------- Database Connectivity Section
public string openLocalDatabaseConnection()
{
try
{
//try to create the connection
_conn = new SqlConnection(_ldb_connection_string);
_conn.Open();
}
catch (Exception e)
{
return string.Concat("Can't connect to LDB with '", e.Message, "'");
}
return ""; //success
}
public string closeLocalDatabaseConnection()
{
_conn.Close();
_conn.Dispose();
return "";
}
I am getting an empty connection string and 'The ConnectionString property has not been initialized' exception thrown. I don't understand as I have numerous other methods in the class which work without issue. Any ideas?
Thanks
You have to call openLocalDatabaseConnection() function before proceeding further so that your SqlConnection Object will be initilised with Connection String Properly.
Code :
public DataTable getMyTable()
{
openLocalDatabaseConnection();
//used for populating the DataGridView
SqlCommand _com = new SqlCommand(string.Format("select * from tab.myTable where Country = 'Angola' "), _conn);
_com.CommandTimeout = _command_timeout;
DataSet _ds = new DataSet();
SqlDataAdapter _adapt = new SqlDataAdapter();
try
{
_adapt.SelectCommand = _com;
int i = _adapt.Fill(_ds, "Asset_Transactions");
if (_ds.Tables.Count > 0)
{
return _ds.Tables[0];
}
else
{
return makeErrorTable("GetMyTable", "No Table Returned for myTable");
}
}
catch (Exception e)
{
return makeErrorTable("GetMyTable", e.Message);
}
}
For example add an application config file to your project(or inside the one you have) and place this(the name and the connection string you place yours of course):
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name ="MyConnection" connectionString ="your connection string here"/>
</connectionStrings>
</configuration>
Then in your _ldb_connection_string:
string _ldb_connection_string = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;

Categories