I'm create the application, but i have one question.
The client write the name of user in textbox, example 3 letters and search in database(access) and add the database.
Example: User: Rui.
and search in database all nameuser "Rui".
//libraries
using Microsoft.VisualStudio.OLE.Interop;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
private void textBox1_TextChanged(object sender, EventArgs e)
{
OleDbConnection conexao = new OleDbConnection(string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source= {0}\Teste.accdb", Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)));
List<string> Users = new List<string>();
OleDbCommand STK = new OleDbCommand($"SELECT NÂșCliente, NomeUser, CodigoPostal, NIF", conexao);
STK.CommandText = $" SELECT* FROM MyTable WHERE Str(Lista_Pokemon) like '*{textBox1.Text}*'";
User.Clear();
//this code is invention, probably is wrong
for(int d=0; d<Stk.Count()-1; d++)
User.Add(...);
}
If you can help my thanks. This project is c#, net framework and the database is Access 2010. At the moment I dont create the class, but if you need tell my, i need created.
You need create a DbReader and move to next row until end:
OleDbCommand STK = new OleDbCommand($"SELECT NÂșCliente, NomeUser, CodigoPostal, NIF", conexao);
STK.CommandText = $" SELECT * FROM MyTable WHERE Str(Lista_Pokemon) like '%{textBox1.Text}%'";
Users.Clear();
var reader = STK.ExecuteReader();
while (reader.Read())
Users.Add(reader["Lista_Pokemon"].ToString());
Threading user input into the query text is considered a dangerous practice in terms of security and also not logically unsafe.
It is better to act "according to the book" with parameters:
OleDbCommand STK = new OleDbCommand();
STK.Connection = conexao;
STK.CommandText = "SELECT * FROM tblCliente WHERE User like #userParameter";
STK.Parameters.AddWithValue("#userParameter", $"%{textBox1.Text}%")
Users.Clear();
var reader = STK.ExecuteReader();
while (reader.Read())
Users.Add(reader["User"].ToString());
Look at the following code.
The using operator is used here to release resources - this is important!
var dataSource = Path.Combine(
Path.GetDirectoryName(Assembly.GetEntryAssembly().Location),
"Teste.accdb");
var builder = new OleDbConnectionStringBuilder();
builder.Provider = "Microsoft.ACE.OLEDB.12.0";
builder.DataSource = dataSource;
var connectionString = builder.ToString();
var sql = "SELECT ..."; // place your query here
using (var connection = new OleDbConnection(connectionString))
{
connection.Open();
using (var command = new OleDbCommand(sql, connection))
using (var reader = command.ExecuteReader())
{
var users = new List<User>();
while (reader.Read())
{
var user = new User();
user.ClientNumber = (int)reader["NÂșCliente"];
user.UserName = (string)reader["NomeUser"];
user.CodigoPostal = (string)reader["CodigoPostal"];
user.NIF = (string)reader["NIF"];
users.Add(user);
}
// return users; // Return data from method
}
}
This class is used for storing user data.
Change the property names and types to the ones you need.
class User
{
public int ClientNumber { get; set; }
public string UserName { get; set; }
public string CodigoPostal { get; set; }
public string NIF { get; set; }
}
And, of course, use parameters in sql queries, as #dovid showed in his example.
Thanks Alexander Petrov and dovid, givend the solution to my problem. But i "found" the solution and i send.
OleDbConnection conexao = new OleDbConnection(string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source= {0}\Teste.accdb", Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)));
OleDbCommand STK = new OleDbCommand("SELECT * FROM MyTable ORDER BY Id");
conexao.Open();
comando.Connection = STK;
var reader = comando.ExecuteReader();
var users = new List<User>();
while (reader.Read())
{
var user = new User();
user.ClientNumber = (reader["ClientNumber "]);
user.UserName= reader["UserName"];
user.CodigoPostal= reader["CodigoPostal"];
user.NIF= reader["NIF"];
users.Add(user);
}
class User
{
public string ClientNumber { get; set; }
public string UserName { get; set; }
public string CodigoPostal { get; set; }
public string NIF { get; set; }
}
Related
I have the following code to query the database, get the data, set each property for the object, and then return that object. In this case, it is an impact object that has the properties FinancialImpactId and EffectiveDate.
Throughout my project I query the database several times like the example below using objects that have the associated property name in the database.
Is there a way to create a generic reusable class that would take in the following parameters: object to be returned or the type, the connection, and the query text?
It would then return the object and set each property like below but dynamically and would be reusable.
try
{
using (var conn = new SqlConnection())
{
conn.ConnectionString = connection.ConnectionString;
conn.Open();
using (var cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = " SELECT TOP 1 fi.financialimpactid,
fi.effectivedate " +
" FROM FinancialImpact fi " +
" INNER JOIN [Case] c ON c.caseid =
fi.caseid " +
" WHERE fi.isDeleted = 0 AND
c.IsDeleted = 0";
var reader = cmd.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
impact.FinancialImpactId = reader.GetInt32(0);
impact.EffectiveDate = reader.GetDateTime(1);
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
An ORM like Entity Framework is certainly the better option here, but you can absolutely create a class that could query the database this way. You won't have parametrised queries or transactions, and you really won't save that much in re-usability, since every time you call it you'd need to provide lots of code to get it to function in the first place.
An example. Take a query class:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
namespace QueryExample {
public class Query {
private readonly SqlConnection _connection;
public Query(SqlConnection connection) {
_connection = connection;
}
public IEnumerable<T> Run<T>(string text, Func<SqlDataReader, T> builder) {
var results = new List<T>();
try {
_connection.Open();
using (var command = new SqlCommand()) {
command.Connection = _connection;
command.CommandType = CommandType.Text;
command.CommandText = text;
var reader = command.ExecuteReader();
if (reader.HasRows)
while (reader.Read())
results.Add(builder(reader));
}
_connection.Close();
} catch (Exception e) {
Console.WriteLine(e.Message);
}
return results;
}
}
}
...now take an example of running this class:
using System;
using System.Data.SqlClient;
namespace QueryExample {
public class Example {
public static void Run() {
using (var connection = new SqlConnection(string.Empty)) {
var query = new Query(connection);
const string text = "SELECT TOP 1 fi.financialimpactid, " +
"fi.effectivedate " +
" FROM FinancialImpact fi " +
" INNER JOIN [Case] c ON c.caseid = " +
"fi.caseid " +
" WHERE fi.isDeleted = 0 AND " +
"c.IsDeleted = 0";
var results = query.Run(text, GetData);
// do something with the results
}
}
private static Data GetData(SqlDataReader reader) => new Data {
FinancialImpactId = reader.GetInt32(0),
EffectiveDate = reader.GetDateTime(1)
};
}
internal class Data {
public int FinancialImpactId { get; set; }
public DateTime EffectiveDate { get; set; }
}
}
You see how running the class doesn't give you that much usability, especially since you will always have to return a result (making INSERT INTO, UPDATE and DELETE "result builders" more difficult to define), and it always has to be a list (not as big of a problem, but always having to do an empty check and accessing the first record can get old fast)?
This is one reason why you'd use an ORM nowadays. They not only simplify query creation, but also make parametrisation unnecessary.
I have a SQLite database. I currently can insert, update and delete records in the database. I have a few combo boxes inside of my program are loaded with the information from my datatable. Currently, for me to get the combo boxes to refresh I must quit the program and start it again to get them to refresh.
I am trying to figure out how I can get the combobox to update once I have entered or edited a record.
The following is my code. I am only showing one combobox that I am trying to update. The comboBoxNameRetrival() is where I am using a query to load my combobox data.
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.SQLite;
namespace Baby_Tracker
{
public partial class BabyTracker : Form
{
BabyEntryForm babyEntryForm = new BabyEntryForm();
BabyUpdateForm babyUpdateForm = new BabyUpdateForm();
BabyDeleteForm babyDeleteForm = new BabyDeleteForm();
public BabyTracker()
{
InitializeComponent();
comboBoxNameRetrival();
}
/*
* Allows for the BabyEntryForm to be opened for the user to
* add a new entry for a baby.
*/
private void newBaby_btn_Click(object sender, EventArgs e)
{
babyEntryForm.Show();
}
/*
* Allows for the BabyUpdateForm to be opened for the user to
* add a updated entry for a baby.
*/
private void editBaby_btn_Click(object sender, EventArgs e)
{
babyUpdateForm.Show();
}
/*
* Calls the FirstName table from the SQLite database to be displayed inside
* the combob box. This is also set to refresh as a new baby is entered into the
* application.
*/
public void comboBoxNameRetrival()
{
DataTable dt = new DataTable();
string connectionString = "Data Source = BabyDatabase.sqlite; Version=3;";
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
using (SQLiteDataAdapter da = new SQLiteDataAdapter("SELECT FirstName FROM BabyList", connection))
{
dt.Clear();
da.Fill(dt);
babySelector_cmbo.DisplayMember = "FirstName";
babySelector_cmbo.DataSource = dt;
connection.Close();
}
}
}
/*
* Used for the selection of the combobox name to be changed throughout the program
* as needed. Also, the image for each baby is changed here where the path is called
* from the database to then load the image for each baby based off of the selection
* from the combobox
*
* Note: The heart of changing data between differenet babies.
*/
private void babySelector_cmbo_SelectedIndexChanged(object sender, EventArgs e)
{
name_lb.Text = babySelector_cmbo.GetItemText(babySelector_cmbo.SelectedItem); //loads the selected name from combobox to theis label
string query = "SELECT BabyImagePath FROM BabyList where FirstName = '" + babySelector_cmbo.GetItemText(babySelector_cmbo.SelectedItem) + "'";
string connectionString = "Data Source = BabyDatabase.sqlite; Version=3;";
SQLiteConnection connection = new SQLiteConnection(connectionString);
SQLiteCommand command = new SQLiteCommand(query, connection);
connection.Open();
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string result = Convert.ToString(reader["BabyImagePath"]);
userImage_box.Image = Image.FromFile(result);
}
}
/*
* Calls the BabyDeleteForm to allow for the user to delete an
* baby entry.
*/
private void deleteBaby_btn_Click(object sender, EventArgs e)
{
babyDeleteForm.Show();
}
}
}
This the class where I am doing all of my updates and adding to the database. The addBabyConnection() method is where I am adding a new user. Here is where I am excepting to call the comboBoxNameRetrival() method in the previous class to update that combobox.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Baby_Tracker
{
class AddUpdateDeleteBaby
{
//String declarations
public string path;
public string targetPath;
/*
* Method is using the data from the BabyEntryForm textboxes to create a new row for
* each new baby entered. The connection and all database requires are set up here.
* BabyList is the table that is being used for the storage of the information.
*/
public void addBabyConnection()
{
string connectionString = "Data Source = BabyDatabase.sqlite; Version=3;";
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
using (SQLiteCommand command = conn.CreateCommand())
{
command.CommandText = "INSERT INTO BabyList (ID, FirstName, MiddleName, LastName, DOB, BirthWeight, BirthLength, BirthHeadCir, BabyImagePath) VALUES (#id, #firstName, #middleName, #lastName, #DOB, #birthWeight, #birthLength, #birthHeadCir, #babyImagePath)";
command.Parameters.AddWithValue("#id", null);
command.Parameters.AddWithValue("#firstName", BabyEntryForm.firstName);
command.Parameters.AddWithValue("#middleName", BabyEntryForm.middleName);
command.Parameters.AddWithValue("#lastName", BabyEntryForm.lastName);
command.Parameters.AddWithValue("#DOB", BabyEntryForm.dob);
command.Parameters.AddWithValue("#birthWeight", BabyEntryForm.weight);
command.Parameters.AddWithValue("#birthLength", BabyEntryForm.length);
command.Parameters.AddWithValue("#birthHeadCir", BabyEntryForm.headCir);
command.Parameters.AddWithValue("#babyImagePath", BabyEntryForm.imagePath);
conn.Open();
command.ExecuteNonQuery();
BabyTracker bt = new BabyTracker();
bt.comboBoxNameRetrival();
}
}
/* Allows for a image to be selected for the baby entry. This is called via
* both new baby entry and also update baby entry. Only JPEG na dPNG images
* are accepted here. The files are then saved to a folder (BabyImages) in
* the application.
*/
public void babyImagePath()
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.InitialDirectory = #"C:\";
openFileDialog.Title = "Selet Baby Profile Image";
openFileDialog.Filter = "Image files (*.jpg, *.jpeg, *.png) | *.jpg; *.jpeg; *.png";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
path = #"C:\Users\Brandon\Documents\Visual Studio 2017\Projects\Baby_Tracker\Baby_Tracker\BabyImages"; //save to file location
targetPath = Path.Combine(path, Path.GetFileName(openFileDialog.FileName));
File.Copy(openFileDialog.FileName, targetPath, true);
}
}
/* Connections to the database to use the information entered from the
* BabyUpdateForm to update the database based upon the fields that
* have entered data.
*/
public void updateBaby()
{
string connectionString = "Data Source = BabyDatabase.sqlite; Version=3;";
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
using (SQLiteCommand command = conn.CreateCommand())
{
command.CommandText = "UPDATE BabyList SET FirstName = #firstName, MiddleName = #middleName, LastName = #lastName, DOB = #DOB, BirthWeight = #birthWeight, BirthLength = #birthLength, BirthHeadCir = #birthHeadCir, BabyImagePath = #babyImagePath WHERE FirstName = '"+BabyUpdateForm.comboName+"'";
command.Parameters.AddWithValue("#firstName", BabyUpdateForm.updateFirstName);
command.Parameters.AddWithValue("#middleName", BabyUpdateForm.updateMiddleName);
command.Parameters.AddWithValue("#lastName", BabyUpdateForm.updateLastName);
command.Parameters.AddWithValue("#DOB", BabyUpdateForm.updatedob);
command.Parameters.AddWithValue("#birthWeight", BabyUpdateForm.updateWeight);
command.Parameters.AddWithValue("#birthLength", BabyUpdateForm.updateLength);
command.Parameters.AddWithValue("#birthHeadCir", BabyUpdateForm.updateHeadCir);
command.Parameters.AddWithValue("#babyImagePath", BabyUpdateForm.updateImagePath);
conn.Open();
command.ExecuteNonQuery();
}
}
/* Connects to the database to allow for the user to delete a baby
* entry that they have previously made. Once a baby is deleted
* from the database, all data is lost on the baby and must
* be reentered as a new baby.
*/
public void deletebaby()
{
string connectionString = "Data Source = BabyDatabase.sqlite; Version=3;";
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
using (SQLiteCommand command = conn.CreateCommand())
{
command.CommandText = "DELETE FROM BabyList WHERE FirstName = '" + BabyDeleteForm.comboName + "'";
conn.Open();
command.ExecuteNonQuery();
}
}
}
}
I'm a new C# coder and I am also new with Microsoft SQL Server. The code I have written will parse data from a file using filehelpers and then will place that data in a SQL table. My question is whether it can parse the data but only place part of the string in the SQL server. For example, here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FileHelpers;
using System.Data.SqlClient;
using System.IO;
namespace OnQ_prototype
{
class Report
{
[DelimitedRecord("\t")]
[IgnoreEmptyLines()]
public class ColumnReportNames
{
public String textbox22;
public String textbox29;
public String textbox24;
public String textbox23;
public String PSFullAcct;
public String AccountDescription;
public String BusDateAmount;
public String ThisPTDAmount;
public String LastPTDAmount;
public String ThisYTDAmount;
public String LastYTDAmount;
public String BusDatePctAvail;
public String ThisPTDPctAvail;
public String LastPTDPctAvail;
public String ThisYTDPctAvail;
public String LastYTDPctAvail;
}
static void ProcessFilesCSVFiles(string originalPath, string destinationPath)
{
foreach (var GenesisDirectory in Directory.GetDirectories(originalPath))
{
foreach (var inputFile in Directory.GetFiles(GenesisDirectory, "*.csv"))
{
string lines = inputFile;
FileHelperEngine engine = new FileHelperEngine(typeof(ColumnReportNames));
var records = engine.ReadFile(lines) as ColumnReportNames[];
foreach (var record in records)
{
SqlCommand cmd;
SqlConnection conn;
conn = new SqlConnection("Data Source=hureports01;Initial Catalog=hureports;Integrated Security=True");
conn.Open();
var sqlCommand = string.Format(#"MERGE [OnQReport] AS target USING (select #Property as Property, #Date_of_Report as Date_of_Report, #Percent_Occupancy_PAR as Percent_Occupancy_PAR, #val as {0}) AS source ON (target.Date_of_Report = source.Date_of_Report) WHEN MATCHED THEN UPDATE SET {0}= source.{0} WHEN NOT MATCHED THEN INSERT (Property, Date_of_Report, Percent_Occupancy_PAR, {0}) VALUES (source.Property, source.Date_of_Report, Percent_Occupancy_PAR, source.{0});", column);
cmd = new SqlCommand(sqlCommand, conn);
cmd.Parameters.AddWithValue("#Property", record.textbox24);
cmd.Parameters.AddWithValue("#Date_of_Report", record.textbox23);
cmd.Parameters.AddWithValue("#Percent_Occupancy_PAR", amount2);
cmd.Parameters.AddWithValue("#val", amount);
cmd.ExecuteNonQuery();
conn.Close();
}
So one of the values I am adding is Date_of_Report which is located in textbox23. However, the value of textbox23 is Business Date: 6/14/2016. Is there a way for it to only put the date in Date_of_Report (i.e. get rid of "Business Date:"
Try this:
string[] getDate = textBoxVal.Split(':');
string dateOfReport = getDate[1];
Are you storing this as a SQL datetime? You may want to convert it afterward.
Relevant fiddle: https://dotnetfiddle.net/ql40kl
I'm trying to get all data from an SQL table and store it in a List using the C# programming language.
the SQL statement I'm using is:
private string cmdShowEmployees = "SELECT * FROM Employees;";
This is being used in the same class as a function
public List<string> showAllIdData()
{
List<string> id = new List<string>();
using (sqlConnection = getSqlConnection())
{
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = cmdShowEmployees;
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read()) {
id.Add(reader[0].ToString());
}
return id;
}
}
and here
public List<string> showAllActiveData()
{
List<string> active = new List<string>();
using (sqlConnection = getSqlConnection())
{
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = cmdShowEmployees;
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read()) {
active.Add(reader[1].ToString());
}
return active;
}
I would have to create 9 more functions this way in order to get all the data out of the Employees table. This seems very inefficient and I was wondering if there was a more elegant way to do this.
I know using an adapter is one way to do it but I don't think it is possible to convert a filled adapter to a list, list list etc.
SqlDataAdapter adapter = sqlDataCollection.getAdapter();
DataSet dataset = new DataSet();
adapter.Fill(dataset, "idEmployees");
dataGridView1.DataSource = dataset;
dataGridView1.DataMember = "idEmployees";
Any ideas?
If you must use the reader in this way, why not create an object which holds the table row data.
public class SomeComplexItem
{
public string SomeColumnValue { get; set;}
public string SomeColumnValue2 { get; set;}
public string SomeColumnValue3 { get; set;}
public string SomeColumnValue4 { get; set;}
}
That way you can loop through with your reader as follows:
public List<SomeComplexItem> showAllActiveData()
{
List<SomeComplexItem> active = new List<SomeComplexItem>();
using (sqlConnection = getSqlConnection())
{
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = cmdShowEmployees;
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read())
{
var someComplexItem = new SomeComplexItem();
someComplexItem.SomeColumnValue = reader[1].ToString();
someComplexItem.SomeColumnValue2 = reader[2].ToString();
someComplexItem.SomeColumnValue3 = reader[3].ToString();
active.Add(someComplexItem);
}
return active;
}
You could use two select statements to populate two List<string> as shown in the example below where the key between reads is reader.NextResult();.
The database used is the standard Microsoft NorthWind database.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
namespace SQL_Server_TwoList
{
public class DataOperations
{
public List<string> Titles { get; set; }
public List<string> Names { get; set; }
/// <summary>
/// Trigger code to load two list above
/// </summary>
public DataOperations()
{
Titles = new List<string>();
Names = new List<string>();
}
public bool LoadData()
{
try
{
using (SqlConnection cn = new SqlConnection(Properties.Settings.Default.ConnectionString))
{
string commandText = #"
SELECT [TitleOfCourtesy] + ' ' + [LastName] + ' ' + [FirstName] As FullName FROM [NORTHWND.MDF].[dbo].[Employees];
SELECT DISTINCT [Title] FROM [NORTHWND.MDF].[dbo].[Employees];";
using (SqlCommand cmd = new SqlCommand(commandText, cn))
{
cn.Open();
SqlDataReader reader = cmd.ExecuteReader();
// get results into first list from first select
if (reader.HasRows)
{
while (reader.Read())
{
Names.Add(reader.GetString(0));
}
// move on to second select
reader.NextResult();
// get results into first list from first select
if (reader.HasRows)
{
while (reader.Read())
{
Titles.Add(reader.GetString(0));
}
}
}
}
}
return true;
}
catch (Exception)
{
return false;
}
}
}
}
Form code
namespace SQL_Server_TwoList
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DataOperations dataOps = new DataOperations();
if (dataOps.LoadData())
{
listBox1.DataSource = dataOps.Names;
listBox2.DataSource = dataOps.Titles;
}
}
}
}
You could always add it all to a dataset or datatable instead of looping through using datareader to add to an array, dataset allows you to access data in similar way to array anyway.
Connstr = "Data Source = " + SelectedIP + "; Initial Catalog = " + dbName + "; User ID = " + txtUsername.Text +"; Password = "+ txtPassword.Text +"";
conn = new SqlConnection(Connstr);
try
{
string contents = "SELECT * FROM ..."
conn.Open();
SqlDataAdapter da_1 = new SqlDataAdapter(contents, conn); //create command using contents of sql file
da_1.SelectCommand.CommandTimeout = 120; //set timeout in seconds
DataSet ds_1 = new DataSet(); //create dataset to hold any errors that are rturned from the database
try
{
//manipulate database
da_1.Fill(ds_1);
if (ds_1.Tables[0].Rows.Count > 0) //loop through all rows of dataset
{
for (int i = 0; i < ds_1.Tables[0].Rows.Count; i++)
{
//rows[rownumber][column number/ "columnName"]
Console.Write(ds_1.Tables[0].Rows[i][0].ToString() + " ");
}
}
}
catch(Exception err)
{}
conn.Close();
}
catch(Exception ex)
{}
I'm having a problem with C# and sql connection. when it comes to C# I'm a noobie and have pretty much no idea what I'm doing :/ I am trying to follow a tutorial which explaines how to do everything step by step and for some reason it doesn't work when I try to do it on my database and application.
This is my Form1.cs
using System;
using System.Collections;
using System.Windows.Forms;
namespace Praca_Inzynierska
{
public partial class Form1 : Form
{
private Connection sqlCon = new Connection();
private ArrayList list = new ArrayList();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'restaurantDataSet2.Employees' table. You can move, or remove it, as needed.
this.employeesTableAdapter.Fill(this.restaurantDataSet2.Employees);
FillTextFieldsEmployees(1);
}
public void FillTextFieldsEmployees(int EmployeeID)
{
list = sqlCon.GetAllEmployees(EmployeeID);
textFirstName.Text = list[0].ToString();
textLastName.Text = list[1].ToString();
textAdress.Text = list[2].ToString();
textCity.Text = list[3].ToString();
textPhoneNumber.Text = list[4].ToString();
textEmail.Text = list[5].ToString();
textBirthDate.Text = list[6].ToString();
textAge.Text = list[7].ToString();
textGender.Text = list[8].ToString();
textTitle.Text = list[9].ToString();
textSalary.Text = list[10].ToString();
}
private void dataGridViewEmployees_CellClick(object sender, DataGridViewCellEventArgs e)
{
var currentRowIndex = dataGridViewEmployees.SelectedCells[0].RowIndex;
int currentIndex = (int) dataGridViewEmployees.Rows[currentRowIndex].Cells[0].Value;
FillTextFieldsEmployees(currentIndex);
}
}
}
This is my class Connection
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
namespace Praca_Inzynierska
{
public class Connection
{
private String connectionString = "Data Source = MAKSKOMP\\SQL2012EXP; Initial Catalog = Restaurant;Integrated Security = True";
public ArrayList GetAllEmployees(int EmployeeID)
{
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
String query = "SELECT * FROM Employees WHERE EmployeeID = '" + EmployeeID +"'";
using (var command = new SqlCommand(query, connection))
{
var reader = command.ExecuteReader();
var list = new ArrayList();
while (reader.Read())
{
String FirstName = reader.GetString(1);
String LastName = reader.GetString(2);
String Adress = reader.GetString(3);
String City = reader.GetString(4);
String PhoneNumber = reader.GetString(5);
String Email = reader.GetString(6);
DateTime BirthDate = reader.GetDateTime(7);
Int16 Age = reader.GetInt16(8);
String Gender = reader.GetString(9);
String Title = reader.GetString(10);
int Salary = reader.GetInt32(11);
list.Add(FirstName);
list.Add(LastName);
list.Add(Adress);
list.Add(City);
list.Add(PhoneNumber);
list.Add(Email);
list.Add(BirthDate);
list.Add(Age);
list.Add(Gender);
list.Add(Title);
list.Add(Salary);
}
connection.Close();
reader.Close();
return list;
}
}
}
}
}
and for some reason it breaks in this particular place
int currentIndex = (int) dataGridViewEmployees.Rows[currentRowIndex].Cells[0].Value;
I have tried to debug it step by step and also it doesn't finish this loop
while (reader.Read())
{
String FirstName = reader.GetString(1);
String LastName = reader.GetString(2);
String Adress = reader.GetString(3);
String City = reader.GetString(4);
String PhoneNumber = reader.GetString(5);
String Email = reader.GetString(6);
DateTime BirthDate = reader.GetDateTime(7);
Int16 Age = reader.GetInt16(8);
String Gender = reader.GetString(9);
String Title = reader.GetString(10);
int Salary = reader.GetInt32(11);
list.Add(FirstName);
list.Add(LastName);
list.Add(Adress);
list.Add(City);
list.Add(PhoneNumber);
list.Add(Email);
list.Add(BirthDate);
list.Add(Age);
list.Add(Gender);
list.Add(Title);
list.Add(Salary);
}
it ends on
Int16 Age = reader.GetInt16(8);
Since your code already uses a Data Bound grid, try binding the TextBox controls to the same binding source as well. It doesn't make much sense to fetch the data from the database when the data is already loaded into the grid...