My code selects only first entry, but I'm need to select all entries in a table. Is there any way to do it? Thanks!
public string getSiteForRotator()
{
string CommandText = "SELECT `url`, `desc`, `timer` FROM sites";
string Connect = "connection_string";
MySqlConnection myConnection = new MySqlConnection(Connect);
MySqlCommand myCommand = new MySqlCommand(CommandText, myConnection);
myConnection.Open();
MySqlDataReader MyDataReader;
MyDataReader = myCommand.ExecuteReader();
while (MyDataReader.Read())
{
string url = MyDataReader.GetString(0);
string desc = MyDataReader.GetString(1);
int timer = MyDataReader.GetInt32(2);
return url+"," + desc+"," + timer.ToString();
}
MyDataReader.Close();
myConnection.Close();
return "ERROR";
}
As it is now your code return just the first record because in the while loop you exit the method at the first loop with the return that concatenates together the data from the first record. If you want to return all record then
the most simple way, is to use a DataTable
public DataTable getSiteForRotator()
{
DataTable result = new DataTable();
string CommandText = "SELECT `url`, `desc`, `timer` FROM sites";
string Connect = "connection_string";
using(MySqlConnection myConnection = new MySqlConnection(Connect))
using(MySqlDataAdapter da = new MySqlDataAdapter(CommandText))
da.Fill(dt);
return dt;
}
and in your calling code you could check if there are rows in the table and use that rows if there is any of them
DataTable result = getSiteForRotator();
if(result.Rows.Count == 0)
Console.WriteLine("No rows found");
else
... use the rows of the datatable ....
public string getSiteForRotator()
{
string CommandText = "SELECT `url`, `desc`, `timer` FROM sites";
string Connect = "connection_string";
MySqlConnection myConnection = new MySqlConnection(Connect);
MySqlCommand myCommand = new MySqlCommand(CommandText, myConnection);
myConnection.Open();
MySqlDataReader MyDataReader;
MyDataReader = myCommand.ExecuteReader();
string url = "";
while (MyDataReader.Read())
{
url = MyDataReader.GetString(0);
string desc = MyDataReader.GetString(1);
int timer = MyDataReader.GetInt32(2);
url+"," + desc+"," + timer.ToString();
}
MyDataReader.Close();
myConnection.Close();
return url;
}
Is This Helpfull ?? You use return statement in while loop, thats y it only shows single record.
Related
I want insert some data to localdatabace and insert is successfully done but don't show in my datagridview tile second insert do for debog it I Call Select All end of my insert and see the last insert don't show in it but whene i insert a next data , last data will be showing can every one help me pleas?
public void connect()
{
String conString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\hana\\documents\\visual studio 2017\\Projects\\Bank\\Bank\\Database.mdf;Integrated Security=True";
SqlConnection sql = new SqlConnection(conString);
String sqll = "Insert into TblBank (txtTodayDate" +
",txtSahebanHesab" +
",txtShobe" +
",txtShomareMoshtari" +
",txtShoareHesab" +
",cmbNoeHesab" +
",txtSarresid" +
")";
try
{
sql.Open();
SqlDataAdapter sda = new SqlDataAdapter(sqll, sql);
SqlCommand sc = new SqlCommand(sqll,sql);
sc.Parameters.AddWithValue("todayDate", new PersianDateTime(dtpTodayDate.the_date).ToString("yyyy/MM/dd"));
sc.Parameters.AddWithValue("sahebanHesab", txtSahebHesabName.Text);
sc.Parameters.AddWithValue("shobe", txtshobe.Text);
sc.Parameters.AddWithValue("shomareMoshtari", txtShomareMoshtari.Text);
sc.Parameters.AddWithValue("shoareHesab", txtShomareHesab.Text);
sc.Parameters.AddWithValue("noeHesab", cmbNoeHesab.SelectedIndex);
sc.Parameters.AddWithValue("sarresid", txtSarResidMah.Text);
sc.ExecuteNonQuery();
sql.Close();
select();
}
catch (Exception ex)
{
}
}
and select is
private void select()
{
String conString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\hana\\documents\\visual studio 2017\\Projects\\Bank\\Bank\\Database.mdf;Integrated Security=True";
SqlConnection cn = new SqlConnection(conString);
String sqlString = "SELECT * FROM TblBank Order BY Id desc ";
SqlConnection sql = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand(sqlString, cn);
try {
sql.Open();
SqlDataAdapter sa = new SqlDataAdapter(sqlString, sql);
using (SqlDataReader read = sa.SelectCommand.ExecuteReader())
{
if (read.Read())
{
DataTable dt = new DataTable();
dt.Load(read);
this.tblBankDataGridViewX.DataSource = dt;
}
}
sql.Close();
}
catch (Exception ex)
{
}
}
The DataReader.Read() method will iterate result set before DataTable.Load(). Because the DataReader is a forward-only stream, it has empty result set when DataTable.Load() executes and DataTable content is still empty while setting DataSource for DataGridView. Try DataReader.HasRows property to check result set availability:
using (SqlConnection cn = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand(sqlString, cn))
{
try
{
cn.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
// check if the reader returns result set
if (read.HasRows)
{
DataTable dt = new DataTable();
dt.Load(read);
this.tblBankDataGridViewX.DataSource = dt;
}
}
}
catch (Exception ex)
{
// do something
}
}
}
public void addintovisitor()
{
string companyname = (txtvisitor.Text.ToUpper());
DataSet result = new DataSet();
visitorcompany vc = new visitorcompany();
string Location1 = Convert.ToString(Session["location"]);
vc.checksamecompanyname(ref result, Location1);
for (int i = 0; i < result.Tables["details"].Rows.Count; i++)
{
if (companyname == result.Tables["details"].Rows[i]["Companyname"].ToString())
{
}
else
{
string strConn = Convert.ToString(ConfigurationManager.ConnectionStrings["connectionstring"]);
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand(
"INSERT INTO tblVisitorcompany ([CompanyName], " +
"[Location1]) " +
"VALUES(#CompanyName, #Location1)", conn);
cmd.Parameters.AddWithValue("#Companyname", companyname);
cmd.Parameters.AddWithValue("#Location1", Location1);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
My visitorcompany class:
public int checksamecompanyname(ref DataSet result, string Location1)
{
string strConn = Convert.ToString(
ConfigurationManager.ConnectionStrings
["connectionstring"]);
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand
("select Companyname from tblVisitorcompany where Location1 ='" + Location1 + "'", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
conn.Open();
da.Fill(result, "details");
conn.Close();
//Return 0 when no error occurs.
return 0;
}
I am trying to search one row at a time to check whether the sql table got the same companyname. if there is already exisiting companyname, the program will do nothing. If this is a new companyname, the program will add companyname into the sql table. However, when adding new companyname, the program will add more than once. Can someone please help me to re-edit my program such that it only add one new companyname. Many thanks.
using( var connection = new SqlConnection( "my connection string" ) ) {
using( var command = connection.CreateCommand() ) {
command.CommandText = "SELECT Column1, Column2, Column3 FROM myTable";
connection.Open();
using( var reader = command.ExecuteReader() ) {
var indexOfColumn1 = reader.GetOrdinal( "Column1" );
var indexOfColumn2 = reader.GetOrdinal( "Column2" );
var indexOfColumn3 = reader.GetOrdinal( "Column3" );
while( reader.Read() ) {
var value1 = reader.GetValue( indexOfColumn1 );
var value2 = reader.GetValue( indexOfColumn2 );
var value3 = reader.GetValue( indexOfColumn3 );
// now, do something what you want
}
}
connection.Close();
}
dont use companyname as an argument of your insert command, since it is stays the same in for loop. Use result.Tables["details"].Rows[i]["Companyname"].ToString() instead:
...
cmd.Parameters.AddWithValue("#Companyname", result.Tables["details"].Rows[i]["Companyname"].ToString());
...
Check if the value exists, then add it if not.
A simple change in your code:
bool valueFound = false;
// check if the value exists
for (int i = 0; i < result.Tables["details"].Rows.Count; i++)
{
if (companyname == result.Tables["details"].Rows[i]["Companyname"].ToString())
{
// it exists so we exit the loop
valueFound = true;
break;
}
}
// we have looped all the way without finding the value, so we can insert
if(!valueFound)
{
string strConn = Convert.ToString(ConfigurationManager.ConnectionStrings["connectionstring"]);
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand(
"INSERT INTO tblVisitorcompany ([CompanyName], " +
"[Location1]) " +
"VALUES(#CompanyName, #Location1)", conn);
cmd.Parameters.AddWithValue("#Companyname", companyname);
cmd.Parameters.AddWithValue("#Location1", Location1);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
Off course you could check if the value exists in a more efficient way, but this should at least solve your specific problem.
I have a database table with 3 columns firstname, Lastname and age. In my C# Windows application I have 3 textboxes called textbox1... I made my connectivity to my SQL Server using this code:
SqlConnection con = new SqlConnection("Data Source = .;
Initial Catalog = domain;
Integrated Security = True");
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tablename", con);
I'd like to get values from my database; if I give a value in textbox1 it has to match the values in the database and retrieve other details to the corresponding textboxes.
I tried this method but it's not working:
cmd.CommandText = "select * from tablename where firstname = '" + textBox1.Text + "' ";
How can I do it to retrieve all the other values to the textboxes?
public Person SomeMethod(string fName)
{
var con = ConfigurationManager.ConnectionStrings["Yourconnection"].ToString();
Person matchingPerson = new Person();
using (SqlConnection myConnection = new SqlConnection(con))
{
string oString = "Select * from Employees where FirstName=#fName";
SqlCommand oCmd = new SqlCommand(oString, myConnection);
oCmd.Parameters.AddWithValue("#Fname", fName);
myConnection.Open();
using (SqlDataReader oReader = oCmd.ExecuteReader())
{
while (oReader.Read())
{
matchingPerson.firstName = oReader["FirstName"].ToString();
matchingPerson.lastName = oReader["LastName"].ToString();
}
myConnection.Close();
}
}
return matchingPerson;
}
Few things to note here: I used a parametrized query, which makes your code safer. The way you are making the select statement with the "where x = "+ Textbox.Text +"" part opens you up to SQL injection.
I've changed this to:
"Select * from Employees where FirstName=#fName"
oCmd.Parameters.AddWithValue("#fname", fName);
So what this block of code is going to do is:
Execute an SQL statement against your database, to see if any there are any firstnames matching the one you provided.
If that is the case, that person will be stored in a Person object (see below in my answer for the class).
If there is no match, the properties of the Person object will be null.
Obviously I don't exactly know what you are trying to do, so there's a few things to pay attention to: When there are more then 1 persons with a matching name, only the last one will be saved and returned to you.
If you want to be able to store this data, you can add them to a List<Person> .
Person class to make it cleaner:
public class Person
{
public string firstName { get; set; }
public string lastName { get; set; }
}
Now to call the method:
Person x = SomeMethod("John");
You can then fill your textboxes with values coming from the Person object like so:
txtLastName.Text = x.LastName;
create a class called DbManager:
Class DbManager
{
SqlConnection connection;
SqlCommand command;
public DbManager()
{
connection = new SqlConnection();
connection.ConnectionString = #"Data Source=. \SQLEXPRESS;AttachDbFilename=|DataDirectory|DatabaseName.mdf;Integrated Security=True;User Instance=True";
command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
} // constructor
public bool GetUsersData(ref string lastname, ref string firstname, ref string age)
{
bool returnvalue = false;
try
{
command.CommandText = "select * from TableName where firstname=#firstname and lastname=#lastname";
command.Parameters.Add("firstname",SqlDbType.VarChar).Value = firstname;
command.Parameters.Add("lastname",SqlDbType.VarChar).Value = lastname;
connection.Open();
SqlDataReader reader= command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
lastname = reader.GetString(1);
firstname = reader.GetString(2);
age = reader.GetString(3);
}
}
returnvalue = true;
}
catch
{ }
finally
{
connection.Close();
}
return returnvalue;
}
then double click the retrieve button(e.g btnretrieve) on your form and insert the following code:
private void btnretrieve_Click(object sender, EventArgs e)
{
try
{
string lastname = null;
string firstname = null;
string age = null;
DbManager db = new DbManager();
bool status = db.GetUsersData(ref surname, ref firstname, ref age);
if (status)
{
txtlastname.Text = surname;
txtfirstname.Text = firstname;
txtAge.Text = age;
}
}
catch
{
}
}
To retrieve data from database:
private SqlConnection Conn;
private void CreateConnection()
{
string ConnStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
Conn = new SqlConnection(ConnStr);
}
public DataTable getData()
{
CreateConnection();
string SqlString = "SELECT * FROM TableName WHERE SomeID = #SomeID;";
SqlDataAdapter sda = new SqlDataAdapter(SqlString, Conn);
DataTable dt = new DataTable();
try
{
Conn.Open();
sda.Fill(dt);
}
catch (SqlException se)
{
throw;
}
catch (Exception ex)
{
throw;
}
finally
{
Conn.Close();
}
return dt;
}
You can use this simple method after setting up your connection:
private void getAgentInfo(string key)//"key" is your search paramter inside database
{
con.Open();
string sqlquery = "SELECT * FROM TableName WHERE firstname = #fName";
SqlCommand command = new SqlCommand(sqlquery, con);
SqlDataReader sReader;
command.Parameters.Clear();
command.Parameters.AddWithValue("#fName", key);
sReader = command.ExecuteReader();
while (sReader.Read())
{
textBoxLastName.Text = sReader["Lastname"].ToString(); //SqlDataReader
//["LastName"] the name of your column you want to retrieve from DB
textBoxAge.Text = sReader["age"].ToString();
//["age"] another column you want to retrieve
}
con.Close();
}
Now you can pass the key to this method by your textBoxFirstName like:
getAgentInfo(textBoxFirstName.Text);
we can use this type of snippet also we generally use this kind of code for testing and validating data for DB to API fields
class Db
{
private readonly static string ConnectionString =
ConfigurationManager.ConnectionStrings
["DbConnectionString"].ConnectionString;
public static List<string> GetValuesFromDB(string LocationCode)
{
List<string> ValuesFromDB = new List<string>();
string LocationqueryString = "select BELocationCode,CityLocation,CityLocationDescription,CountryCode,CountryDescription " +
$"from [CustomerLocations] where LocationCode='{LocationCode}';";
using (SqlConnection Locationconnection =
new SqlConnection(ConnectionString))
{
SqlCommand command = new SqlCommand(LocationqueryString, Locationconnection);
try
{
Locationconnection.Open();
SqlDataReader Locationreader = command.ExecuteReader();
while (Locationreader.Read())
{
for (int i = 0; i <= Locationreader.FieldCount - 1; i++)
{
ValuesFromDB.Add(Locationreader[i].ToString());
}
}
Locationreader.Close();
return ValuesFromDB;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
}
}
hope this might helpful
Note: you guys need connection string (in our case
"DbConnectionString")
DataTable formerSlidesData = new DataTable();
DformerSlidesData = searchAndFilterService.SearchSlideById(ids[i]);
if (formerSlidesData.Rows.Count > 0)
{
DataRow rowa = formerSlidesData.Rows[0];
cabinet = Convert.ToInt32(rowa["cabinet"]);
box = Convert.ToInt32(rowa["box"]);
drawer = Convert.ToInt32(rowa["drawer"]);
}
I ran the SQL Query in SQL Server Management Studio and it worked.
I get the following error in my WinForm C# application
The parameterized query '(#word1 text)SELECT distinct [database].[dbo].[tableName].[n' expects the parameter '#word1', which was not supplied.
Here is my code
private void buttonRunQuery_Click(object sender, EventArgs e)
{
if (connection == null)
{
connection = ConnectionStateToSQLServer();
SqlCommand command = new SqlCommand(null, connection);
command = createSQLQuery(command);
GetData(command);
}
else
{
SqlCommand command = new SqlCommand(null, connection);
command = createSQLQuery(command);
GetData(command);
}
}
private SqlCommand createSQLQuery(SqlCommand command)
{
string[] allTheseWords;
if (textBoxAllTheseWords.Text.Length > 0)
{
allTheseWords = textBoxAllTheseWords.Text.Split(' ');
string SQLQuery = "SELECT distinct [database].[dbo].[customerTable].[name], [database].[dbo].[customerTable].[dos], [database].[dbo].[customerTable].[accountID], [database].[dbo].[reportTable].[customerID], [database].[dbo].[reportTable].[accountID], [database].[dbo].[reportTable].[fullreport] FROM [database].[dbo].[reportTable], [database].[dbo].[customerTable] WHERE ";
int i = 1;
foreach (string word in allTheseWords)
{
var name = "#word" + (i++).ToString();
command.Parameters.Add(name, SqlDbType.Text);
//(name, SqlDbType.Text).Value = word;
SQLQuery = SQLQuery + String.Format(" [database].[dbo].[reportTable].[fullreport] LIKE {0} AND ", name);
}
SQLQuery = SQLQuery + " [database].[dbo].[customerTable].[accountID] = [database].[dbo].[reportTable].[accountID]";
command.CommandText = SQLQuery;
}
MessageBox.Show(command.CommandText.ToString());
return command;
}
public DataTable GetData(SqlCommand cmd)
{
//SqlConnection con = new SqlConnection(connString);
//SqlCommand cmd = new SqlCommand(sqlcmdString, cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
connection.Open();
DataTable dt = new DataTable();
da.Fill(dt);
connection.Close();
return dt;
}
The error is happening on da.Fill(dt)
Any suggestions would be helpful
Thank you
In your example, you have commented out the line where you set the value of the Parameter:
command.Parameters.Add(name, SqlDbType.Text);
//(name, SqlDbType.Text).Value = word;
If you do not set a value for a parameter, it is ignored (and won't exist).
Change to this:
command.Parameters.AddWithValue(name, word);
For clarity, consider this quote:
The value to be added. Use DBNull.Value instead of null, to indicate a null value.
From here: SqlParameterCollection.AddWithValue Method
On var name = "#word" + (i++).ToString(); use just i, increment somewhere else.
I have a database table with 3 columns firstname, Lastname and age. In my C# Windows application I have 3 textboxes called textbox1... I made my connectivity to my SQL Server using this code:
SqlConnection con = new SqlConnection("Data Source = .;
Initial Catalog = domain;
Integrated Security = True");
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tablename", con);
I'd like to get values from my database; if I give a value in textbox1 it has to match the values in the database and retrieve other details to the corresponding textboxes.
I tried this method but it's not working:
cmd.CommandText = "select * from tablename where firstname = '" + textBox1.Text + "' ";
How can I do it to retrieve all the other values to the textboxes?
public Person SomeMethod(string fName)
{
var con = ConfigurationManager.ConnectionStrings["Yourconnection"].ToString();
Person matchingPerson = new Person();
using (SqlConnection myConnection = new SqlConnection(con))
{
string oString = "Select * from Employees where FirstName=#fName";
SqlCommand oCmd = new SqlCommand(oString, myConnection);
oCmd.Parameters.AddWithValue("#Fname", fName);
myConnection.Open();
using (SqlDataReader oReader = oCmd.ExecuteReader())
{
while (oReader.Read())
{
matchingPerson.firstName = oReader["FirstName"].ToString();
matchingPerson.lastName = oReader["LastName"].ToString();
}
myConnection.Close();
}
}
return matchingPerson;
}
Few things to note here: I used a parametrized query, which makes your code safer. The way you are making the select statement with the "where x = "+ Textbox.Text +"" part opens you up to SQL injection.
I've changed this to:
"Select * from Employees where FirstName=#fName"
oCmd.Parameters.AddWithValue("#fname", fName);
So what this block of code is going to do is:
Execute an SQL statement against your database, to see if any there are any firstnames matching the one you provided.
If that is the case, that person will be stored in a Person object (see below in my answer for the class).
If there is no match, the properties of the Person object will be null.
Obviously I don't exactly know what you are trying to do, so there's a few things to pay attention to: When there are more then 1 persons with a matching name, only the last one will be saved and returned to you.
If you want to be able to store this data, you can add them to a List<Person> .
Person class to make it cleaner:
public class Person
{
public string firstName { get; set; }
public string lastName { get; set; }
}
Now to call the method:
Person x = SomeMethod("John");
You can then fill your textboxes with values coming from the Person object like so:
txtLastName.Text = x.LastName;
create a class called DbManager:
Class DbManager
{
SqlConnection connection;
SqlCommand command;
public DbManager()
{
connection = new SqlConnection();
connection.ConnectionString = #"Data Source=. \SQLEXPRESS;AttachDbFilename=|DataDirectory|DatabaseName.mdf;Integrated Security=True;User Instance=True";
command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
} // constructor
public bool GetUsersData(ref string lastname, ref string firstname, ref string age)
{
bool returnvalue = false;
try
{
command.CommandText = "select * from TableName where firstname=#firstname and lastname=#lastname";
command.Parameters.Add("firstname",SqlDbType.VarChar).Value = firstname;
command.Parameters.Add("lastname",SqlDbType.VarChar).Value = lastname;
connection.Open();
SqlDataReader reader= command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
lastname = reader.GetString(1);
firstname = reader.GetString(2);
age = reader.GetString(3);
}
}
returnvalue = true;
}
catch
{ }
finally
{
connection.Close();
}
return returnvalue;
}
then double click the retrieve button(e.g btnretrieve) on your form and insert the following code:
private void btnretrieve_Click(object sender, EventArgs e)
{
try
{
string lastname = null;
string firstname = null;
string age = null;
DbManager db = new DbManager();
bool status = db.GetUsersData(ref surname, ref firstname, ref age);
if (status)
{
txtlastname.Text = surname;
txtfirstname.Text = firstname;
txtAge.Text = age;
}
}
catch
{
}
}
To retrieve data from database:
private SqlConnection Conn;
private void CreateConnection()
{
string ConnStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
Conn = new SqlConnection(ConnStr);
}
public DataTable getData()
{
CreateConnection();
string SqlString = "SELECT * FROM TableName WHERE SomeID = #SomeID;";
SqlDataAdapter sda = new SqlDataAdapter(SqlString, Conn);
DataTable dt = new DataTable();
try
{
Conn.Open();
sda.Fill(dt);
}
catch (SqlException se)
{
throw;
}
catch (Exception ex)
{
throw;
}
finally
{
Conn.Close();
}
return dt;
}
You can use this simple method after setting up your connection:
private void getAgentInfo(string key)//"key" is your search paramter inside database
{
con.Open();
string sqlquery = "SELECT * FROM TableName WHERE firstname = #fName";
SqlCommand command = new SqlCommand(sqlquery, con);
SqlDataReader sReader;
command.Parameters.Clear();
command.Parameters.AddWithValue("#fName", key);
sReader = command.ExecuteReader();
while (sReader.Read())
{
textBoxLastName.Text = sReader["Lastname"].ToString(); //SqlDataReader
//["LastName"] the name of your column you want to retrieve from DB
textBoxAge.Text = sReader["age"].ToString();
//["age"] another column you want to retrieve
}
con.Close();
}
Now you can pass the key to this method by your textBoxFirstName like:
getAgentInfo(textBoxFirstName.Text);
we can use this type of snippet also we generally use this kind of code for testing and validating data for DB to API fields
class Db
{
private readonly static string ConnectionString =
ConfigurationManager.ConnectionStrings
["DbConnectionString"].ConnectionString;
public static List<string> GetValuesFromDB(string LocationCode)
{
List<string> ValuesFromDB = new List<string>();
string LocationqueryString = "select BELocationCode,CityLocation,CityLocationDescription,CountryCode,CountryDescription " +
$"from [CustomerLocations] where LocationCode='{LocationCode}';";
using (SqlConnection Locationconnection =
new SqlConnection(ConnectionString))
{
SqlCommand command = new SqlCommand(LocationqueryString, Locationconnection);
try
{
Locationconnection.Open();
SqlDataReader Locationreader = command.ExecuteReader();
while (Locationreader.Read())
{
for (int i = 0; i <= Locationreader.FieldCount - 1; i++)
{
ValuesFromDB.Add(Locationreader[i].ToString());
}
}
Locationreader.Close();
return ValuesFromDB;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
}
}
hope this might helpful
Note: you guys need connection string (in our case
"DbConnectionString")
DataTable formerSlidesData = new DataTable();
DformerSlidesData = searchAndFilterService.SearchSlideById(ids[i]);
if (formerSlidesData.Rows.Count > 0)
{
DataRow rowa = formerSlidesData.Rows[0];
cabinet = Convert.ToInt32(rowa["cabinet"]);
box = Convert.ToInt32(rowa["box"]);
drawer = Convert.ToInt32(rowa["drawer"]);
}