class that gets a value from database [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
How I will make a class that gets a value from database then display it to textBox?
public static class myMethods
{
public static void getName(string name){
ConnectionStringSettings myConnectionString = ConfigurationManager.ConnectionStrings["LibrarySystem.Properties.Settings.LibraryConnectionString"];
using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
{
myDatabaseConnection.Open();
using (SqlCommand mySqlCommand = new SqlCommand("select Top 1 * from Setting Order By SettingID Desc", myDatabaseConnection))
using (SqlDataReader sqlreader = mySqlCommand.ExecuteReader())
{
if (sqlreader.Read())
{
name = sqlreader["Name"].ToString();
}
}
}
}
}
Form:
private void Button1_Click(object sender, EventArgs e)
{
string name = "";
myMethods.getName(name);
textBox1.Text = name;
}

public static class myMethods
{
public static string getName(){
string name = "";
ConnectionStringSettings myConnectionString = ConfigurationManager.ConnectionStrings["LibrarySystem.Properties.Settings.LibraryConnectionString"];
using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
{
myDatabaseConnection.Open();
using (SqlCommand mySqlCommand = new SqlCommand("select Top 1 * from Setting Order By SettingID Desc", myDatabaseConnection))
using (SqlDataReader sqlreader = mySqlCommand.ExecuteReader())
{
if (sqlreader.Read())
{
name = sqlreader["Name"].ToString();
}
}
}
return name;
}
}
Form:
private void Button1_Click(object sender, EventArgs e)
{
textBox1.Text = myMethods.getName();
}
Or this:
public static class myMethods
{
public static void getName(out string name){
//.....
}
}
private void Button1_Click(object sender, EventArgs e)
{
string name;
myMethods.getName(out name);
textBox1.Text = name;
}

You don't need the parameter:
public static string getName()
{
string result = "";
ConnectionStringSettings myConnectionString = ConfigurationManager.ConnectionStrings["LibrarySystem.Properties.Settings.LibraryConnectionString"];
using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
{
myDatabaseConnection.Open();
using (SqlCommand mySqlCommand = new SqlCommand("select Top 1 * from Setting Order By SettingID Desc", myDatabaseConnection))
using (SqlDataReader sqlreader = mySqlCommand.ExecuteReader())
{
if (sqlreader.Read())
{
result = sqlreader["Name"].ToString();
}
}
}
return result;
}
private void Button1_Click(object sender, EventArgs e)
{
textBox1.Text = myMethods.getName();
}

Since you're only returning a single value name, use ExecuteScalar and reduce the select statement to only return name
public static class myMethods
{
public static string getName()
{
string name = "";
ConnectionStringSettings myConnectionString = ConfigurationManager.ConnectionStrings["LibrarySystem.Properties.Settings.LibraryConnectionString"];
using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
{
myDatabaseConnection.Open();
using (SqlCommand mySqlCommand = new SqlCommand("select Top 1 Name from Setting Order By SettingID Desc", myDatabaseConnection))
var NameObj = mySqlCommand.ExecuteScalar()
if NameObj != null then
name = NameObj.ToString()
}
return name;
}
}
Form:
private void Button1_Click(object sender, EventArgs e)
{
string name = "";
name = myMethods.getName();
textBox1.Text = name;
}

Related

executing function/method in button click event

I have this collection as seen in the code below and I am trying to execute the InserData function to insert the data form the collection to my SQL DB table in the Button_Click_1 event and cannot make it work. Any help?
The code takes data from form fields and adds to the Collection. Once the addition is complete and the user is done adding I want the entire collection written to a SQL data table.
public class LotData
{
public string Lot;
public string Description { get; set; }
public int PO { get; set; }
public string MfgPart { get; set; }
}
// code to add from control data to list
ObservableCollection<LotData> lot = new ObservableCollection<LotData>();
private ObservableCollection<LotData> LoadCollectionData()
{
// List<LotData> lot = new List<LotData>();
lot.Add(new LotData()
{
Lot = LotNo.Text,
Description = frmDescription.Text,
PO = int.Parse(frmPO.Text),
MfgPart = frmMfgPart.Text,
});
return lot;
}
//button to add list data to datagrid on form
public void Button_Click(object sender, RoutedEventArgs e)
{
gridLotData.ItemsSource = LoadCollectionData();
LotNo.Text = String.Empty;
frmMfgPart.Text = string.Empty;
frmDescription.Text = String.Empty;
frmMfgPart.Text = string.Empty;
frmPO.Text = string.Empty;
}
private void Button_Click_1(object sender, RoutedEventArgs e)
//send data from DataGrid to database
{
InserData(LotData);
}
public void InserData(LotData lot)
{
string strConn = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\Matthew\\QCast.mdf;Integrated Security=True;Connect Timeout=30";
SqlConnection con = new SqlConnection(strConn);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT into LotData Values (#LotNum)";
cmd.Connection = con
cmd.Parameters.AddWithValue("#LotNum", lot.Lot);
cmd.ExecuteNonQuery();
con.Close();
}
I think you've got a few things in the wrong place and you're recreating the ObservableCollection. You need to iterate over this to add all items to the DB:
private const string strConn = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\Matthew\\QCast.mdf;Integrated Security=True;Connect Timeout=30";
private ObservableCollection<LotData> lot = new ObservableCollection<LotData>();
public Window1()
{
InitializeComponent();
// Bind ItemsSource once
gridLotData.ItemsSource = lot;
}
public void AddDataToGrid_Click(object sender, RoutedEventArgs e)
{
// Read data from form and add to collection
lot.Add(new LotData()
{
Lot = LotNo.Text,
Description = frmDescription.Text,
PO = int.Parse(frmPO.Text),
MfgPart = frmMfgPart.Text,
});
// Clear entry fields
LotNo.Text = String.Empty;
frmMfgPart.Text = string.Empty;
frmDescription.Text = String.Empty;
frmMfgPart.Text = string.Empty;
frmPO.Text = string.Empty;
}
private void WriteCollectionToDb_Click(object sender, RoutedEventArgs e)
{
using (var conn = new SqlConnection(strConn))
{
conn.Open();
try
{
foreach (var lotData in lot)
{
using (var command = new SqlCommand("INSERT into LotData Values (#LotNum)", conn))
{
command.Parameters.AddWithValue("LotNum", lotData.Lot);
command.ExecuteNonQuery();
}
}
}
finally
{
conn.Close();
}
}
}
In InserData, you have to iterate through all the items in the collection and then insert into DB

Using List of <struct> as a datasource to a listview shows object.tostring() instead of DisplayMember

With a list of struct as the Datasource for a Listbox, I am getting the Object.ToString() rather than the expected field value from the struct
This was working OK when I assigned a DataTable as the DataSource after setting the DisplayMember.
However, I wanted to try using a list of struct (int ID, String Name) instead and despite having set DisplayMember to "Name" before assigning the Datasource to the List I get the row object.toString().
Any help would be fantastic.
On Form Load:
private void frmTestProof_Load(object sender, EventArgs e)
{
TestMaker tm = new TestMaker();
tm.LoadMakersToListbox(ref lstboxMaker);
}
class TestMaker
{
public struct MakerRecord
{
public int MakerID;
public String MakerName;
public MakerRecord(int ID, String Name)
{
MakerID = ID;
MakerName = Name;
}
}
public SQLiteConnection DBconn;
public String thisPath = "";
public SQLiteCommand sqlCommand = new SQLiteCommand();
public DataSet dsMaker = new DataSet();
public SQLiteDataAdapter daMaker = new SQLiteDataAdapter();
public TestMaker()
{
thisPath = "c:\\sqlite\\abc.db";
DBconn = new SQLiteConnection(String.Format("Data Source={0};Version=3;", thisPath));
DBconn.Open();
sqlCommand.Connection = DBconn;
sqlCommand.CommandType = CommandType.Text;
}
public List<MakerRecord> GetListOfMakers()
{
List<MakerRecord> makerList = new List<MakerRecord>();
String sqlMaker = "SELECT ID, VehicleMakerName FROM VehicleMakers WHERE VehicleMakerName IS NOT NULL"
;
sqlCommand.CommandText = sqlMaker;
daMaker.SelectCommand = sqlCommand;
try
{
daMaker.Fill(dsMaker, "Makers");
makerList = (from item in dsMaker.Tables["Makers"].AsEnumerable()
select new MakerRecord()
{
MakerID = Convert.ToInt32(item["ID"]),
MakerName = item["VehicleMakerName"].ToString()
}).ToList();
}
catch (Exception ex)
{
MessageBox.Show(String.Format("List of Makers - Error ({0})", ex.Message));
}
return makerList;
}
public void LoadMakersToListbox(ref ListBox lb)
{
lb.Items.Clear();
lb.ValueMember = "MakerID";
lb.DisplayMember = "MakerName";
lb.DataSource = GetListOfMakers();
}
}
Change public String MakerName; to public string MakerName {get;set;} and public int MakerID; to public int MakerID {get;set;}

How to add items to combobox from another class

How can I add items to my comboBox which is in Form1, but the funcion that add items to that combo box is in another class ?
public void comboBox1_Categories_Load()
{
SqlConnection con = new SqlConnection(connection_string);
string select_string = "SELECT * FROM dbo.Categories";
SqlCommand cmd = new SqlCommand(select_string, con);
SqlDataReader myReader;
con.Open();
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
comboBox1.Items.Add(myReader[1]);
}
myReader.Close();
con.Close();
}
Form:
public partial class Form1 : Form
{
private BusinessLayer _businessLayer ;
public Form1()
{
InitializeComponent();
_businessLayer = new BusinessLayer();
}
private void button1_Click(object sender, EventArgs e)
{
var categories = _businessLayer.GetCategories();
comboBox1.DataSource = categories;
}
}
Business Class:
class BusinessLayer
{
private DataLayer _dataLayer;
public BusinessLayer()
{
_dataLayer = new DataLayer();
}
internal List<string> GetCategories()
{
return _dataLayer.RetrieveCatagories();
}
}
Data Layer (you can refactor and extract the connection to another method):
class DataLayer
{
public const string ConnectionString = "my connection string";
internal List<string> RetrieveCatagories()
{
List<string> items = new List<string>();
using (SqlConnection con = new SqlConnection(ConnectionString))
{
string select_string = "SELECT * FROM dbo.Categories";
SqlCommand cmd = new SqlCommand(select_string, con);
con.Open();
SqlDataReader myReader = cmd.ExecuteReader();
while (myReader.Read())
{
items.Add(myReader[1].ToString());
}
myReader.Close();
}
return items;
}
}
You can something like this:
public static OtherClass()
{
public void RetrieveData(ComboBox comboBox)
{
SqlConnection con = new SqlConnection(connection_string);
string select_string = "SELECT * FROM dbo.Categories";
SqlCommand cmd = new SqlCommand(select_string, con);
SqlDataReader myReader;
con.Open();
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
comboBox.Items.Add(myReader[1]);
}
myReader.Close();
con.Close();
}
}
//then the class where your form is
public void comboBox1_Categories_Load()
{
OtherClass.RetrieveData(comboBox1);
}

C# how to load listview

im doing a windows form application to open and load a database. the code needs to show single record view of the records and the listView view however i am stuck on the listVIew part.
here is the following code
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ADOX;
namespace Ex3
{
public partial class changeButton : Form
{
public List<Client> ClientRecords = new List<Client>(); //Creates a list for the records to be stored
public string filename;
public string fileDir;
public string rec;
public bool checkBC;
public bool checkLC;
public string dataBaseFile;
public OleDbConnection conn;
public changeButton()
{
InitializeComponent();
}
int position = 0;
private void Form1_Load(object sender, EventArgs e)
{
credBalBox.Maximum = 9999999999;
savingBalBox.Maximum = 9999999999;
}
private void ConnectToDataBase()
{
try
{
string strConn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
dataBaseFile + ";";
conn = new OleDbConnection(strConn);
conn.Open();
}
catch (OleDbException e)
{
MessageBox.Show("Failed to connect to database: " + e.Message);
}
}
private void nextButton_Click(object sender, EventArgs e)
{
if (position < ClientRecords.Count - 1)
{
position++;
Print();
}
else
{
MessageBox.Show("Outside of the record limit");
}
}
private void previousButton_Click(object sender, EventArgs e)
{
if (position > 0)
{
position--;
Print();
}
else
{
MessageBox.Show("Outside of the record limit");
}
}
public void Print()
{
int positionAdd1;
positionAdd1 = position;
positionAdd1++;
currentRecLab.Text = positionAdd1.ToString();
MaxRecLab.Text = ClientRecords.Count.ToString();
if (position >= 0 && position < ClientRecords.Count)
{
nameBox.Text = ClientRecords[position].Name;
suburbBox.Text = ClientRecords[position].Suburb;
postBox.Text = ClientRecords[position].Postcode;
credBalBox.Text = ClientRecords[position].CreditBal.ToString();
savingBalBox.Text = ClientRecords[position].SavingBal.ToString();
}
else
{
nameBox.Text = "";
suburbBox.Text = "";
postBox.Text = "";
credBalBox.Text = "";
savingBalBox.Text = "";
}
}
private void addButton_Click(object sender, EventArgs e)
{
string sameAddName = "null";
string addName;
string addSuburb;
string addPostcode;
decimal addCredBal;
decimal addSavBal;
addName = nameBox.Text;
addSuburb = suburbBox.Text;
addPostcode = postBox.Text;
addCredBal = decimal.Parse(credBalBox.Text);
addSavBal = decimal.Parse(savingBalBox.Text);
string sqlPrefix = "INSERT INTO Client VALUES ";
string data = "(" + "'" + addName + "','" + addSuburb + "','" + addPostcode + "','" + addCredBal + "','" + addSavBal + "'" + ")";
string sql = sqlPrefix + data;
foreach (Client client in ClientRecords)
{
if (addName == client.Name)
{
sameAddName = "Name is not unique. Please use a unique name";
}
}
if (sameAddName == "null" && addSuburb != null)
{
ClientRecords.Add(new Client(addName, addSuburb, addPostcode, addCredBal, addSavBal));
OleDbCommand cmd = new OleDbCommand(sql, conn);
cmd.ExecuteNonQuery();
int positions = ClientRecords.Count;
currentRecLab.Text = positions.ToString();
MaxRecLab.Text = positions.ToString();
nameBox.Text = addName;
suburbBox.Text = addSuburb;
postBox.Text = addPostcode;
credBalBox.Text = addCredBal.ToString();
savingBalBox.Text = addSavBal.ToString();
position = ClientRecords.Count - 1;
}
else
{
if ((sameAddName != "null") && (addSuburb == "") && (addPostcode == ""))
{
MessageBox.Show(sameAddName + "\nAlso, one of the fields are empty. Please fill it in before adding a new record");
}
else if (sameAddName != "null")
{
MessageBox.Show(sameAddName);
}
}
}
private void removeButton_Click(object sender, EventArgs e)
{
int recPosition = int.Parse(currentRecLab.Text);
recPosition = recPosition - 1;
position = 0;
ClientRecords.Remove(ClientRecords[recPosition]);
Print();
if (MaxRecLab.Text == "0")
{
currentRecLab.Text = "0";
}
}
private void loadButton_Click_1(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand ("SELECT * FROM Client", conn);
using (OleDbDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
Client nClient = new Client(rdr[0].ToString(), rdr[1].ToString(), rdr[2].ToString(), decimal.Parse(rdr[3].ToString()), decimal.Parse(rdr[4].ToString()));
ClientRecords.Add(nClient);
Print();
}
}
}
private void connectButton_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Title = "Select DataBase";
if (dialog.ShowDialog() == DialogResult.OK)
{
dataBaseFile = dialog.FileName;
DatabaseNameBox.Text = dataBaseFile;
ConnectToDataBase();
}
}
private void DatabaseNameBox_TextChanged(object sender, EventArgs e)
{
}
private void label7_Click(object sender, EventArgs e)
{
}
private void nameBox_TextChanged(object sender, EventArgs e)
{
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
public class Client
{
protected string name;
protected string suburb;
protected string postcode;
protected decimal creditBal;
protected decimal savingBal;
public Client(string name, string suburb, string postcode, decimal creditBal, decimal savingBal)
{
this.name = name;
this.suburb = suburb;
this.postcode = postcode;
this.creditBal = creditBal;
this.savingBal = savingBal;
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public string Suburb
{
get
{
return suburb;
}
set
{
suburb = value;
}
}
public string Postcode
{
get
{
return postcode;
}
set
{
postcode = value;
}
}
public decimal CreditBal
{
get
{
return creditBal;
}
set
{
creditBal = value;
}
}
public decimal SavingBal
{
get
{
return savingBal;
}
set
{
savingBal = value;
}
}
}
}
thanks in advance
further info
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
i want to be able to put the code here and when i click the load button from above it should load the listview
To load a listview I would use the following function - it uses a array of string and listviewitem do add items to a listview.
private void LoadListview()
{
string NAME = "John DOE";
string AGE = "30";
string SEX = "MALE";
string DOB = "08/28/1988";
string[] rowa = { NAME, AGE, SEX, DOB };
var listViewItema = new ListViewItem(rowa);
listView1.Items.Add(listViewItema);
listView1.Items.Add(listViewItema);
listView1.Items.Add(listViewItema);
listView1.Items.Add(listViewItema);
}
You can find a step by step detail answer on my website: http://softvernow.com/2018/05/01/create-list-of-objects-and-load-listview-using-c/

combine two methods returning two different values

Hi I have got two methods are returning two different return type of values like int and string and I am executing query inside the method with passing different variables like the below
METHOD 1
private string SelectTransactionHistory(int transactionId, ContextObject contextObject)
{
SqlConnection con;
SqlCommand cmd;
con = new SqlConnection(contextObject.ConnectionString);
con.Open();
string returnvalue = string.Empty;
string selecteQuery = "SELECT Comments
From dbo.TransactionHistory
WHERE TransactionID = '" + transactionId + "'";
cmd = new SqlCommand(selecteQuery, con);
returnvalue = (string)cmd.ExecuteScalar();
con.Close();
return returnvalue;
}
METHOD 2
private int SelectTransactionHistoryID(string comment, ContextObject contextObject)
{
SqlConnection con;
SqlCommand cmd;
con = new SqlConnection(contextObject.ConnectionString);
con.Open();
string query = "SELECT TransactionID
From dbo.TransactionHistory
WHERE Comments = '" + comment + "'";
cmd = new SqlCommand(query, con);
int returnvalue = (int)cmd.ExecuteScalar();
con.Close();
return returnvalue;
}
I am calling these methods in another method like this
int transactionId = SelectTransactionHistoryID(comment, GetContext());
string commentsreturnValue = SelectTransactionHistory(transactionId, GetContext());
how can i combine these two methods to make more generic type..
Would any one have any suggestions on how to do this..
Many Thanks.....
You could create a method to execute any query using ado.net, for sample:
private static T ExecuteQuery<T>(ContextObject contextObject, string query)
{
T result;
using (SqlConnection con = con = new SqlConnection(contextObject.ConnectionString))
{
try
{
con.Open();
using (SqlCommand cmd = cmd = new SqlCommand(query, con))
{
result = (T)cmd.ExecuteScalar();
}
}
catch
{
result = null;
}
finally
{
con.Close();
}
}
returnr result;
}
And pass a query that return a single value (in sql we use TOP 1), something like this:
var resultComment = ExecuteQuery<string>("SELECT TOP 1 Comments From dbo.TransactionHistory WHERE TransactionID = '" + transactionId + "'");
var resultTransactionId = ExecuteQuery<int>("SELECT TOP 1 TransactionID From dbo.TransactionHistory WHERE Comments = '" + comment + "'")
I have all of my infrastructure classes setup to utilize Dapper. However you can replace the dapper extension method with a regular method.
Base Service:
public interface IService
{
T Execute<T>(Func<IDbConnection, T> query);
void Execute(Action<IDbConnection> query);
}
public sealed class Service : IService
{
private readonly string _connectionString;
public Service(string connectionString)
{
_connectionString = connectionString;
}
private IDbConnection CreateConnection()
{
var connection = new SqlConnection(_connectionString);
connection.Open();
return connection;
}
public T Execute<T>(Func<IDbConnection, T> query)
{
using (var connection = CreateConnection())
{
return query(connection);
}
}
public void Execute(Action<IDbConnection> query)
{
using (var connection = CreateConnection())
{
query(connection);
}
}
}
DTO:
public class TransactionHistory
{
public int TransactionID { get; set; }
public string Comments { get; set; }
}
Service:
public interface ITransactionHistoryService
{
IEnumerable<TransactionHistory> GetByTransactionId(int transactionId);
IEnumerable<TransactionHistory> GetByComment(string comment);
}
public sealed class TransactionHistoryService : ITransactionHistoryService
{
// Note SELECT * is frowned upon. Replace with actual column names.
private const string GetByTransactionIdQuery =
"SELECT * FROM dbo.TransactionHistory WHERE TransactionID = #TransactionId";
private const string GetByCommentQuery =
"SELECT * FROM dbo.TransactionHistory WHERE Comments = #Comment";
private readonly IService _service;
public TransactionHistoryService(IService service)
{
_service = service;
}
public IEnumerable<TransactionHistory> GetByTransactionId(int transactionId)
{
var result = _service.Execute(c =>
c.Query<TransactionHistory>(GetByTransactionIdQuery,
new { TransactionId = transactionId }));
return result;
}
public IEnumerable<TransactionHistory> GetByComment(string comment)
{
var result = _service.Execute(c =>
c.Query<TransactionHistory>(GetByCommentQuery,
new { Comment = comment }));
return result;
}
}
You can create a single function as follows- (Not tested)
private string[] SelectTransactionHistory(int transactionId, ContextObject contextObject)
{
string[] returnValues;
SqlConnection con;
SqlCommand cmd;
SqlDataReader reader;
con = new SqlConnection(contextObject.ConnectionString);
con.Open();
string returnvalue = string.Empty;
string selecteQuery = "SELECT TransactionID, Comments From dbo.TransactionHistory WHERE TransactionID = '" + transactionId + "'";
cmd = new SqlCommand(selecteQuery, con);
reader = cmd.ExecuteReader();
while(reader.Read())
{
returnValues[0] = reader["TransactionID"].ToString();
returnValues[1] = reader["Comments"].ToString();
}
con.Close();
return returnValues;
}
And then call it as follows-
string[] TransactionHistory = SelectTransactionHistory(transactionId, GetContext());
int transactionId = Convert.ToInt32(TransactionHistory[0]);
string commentsreturnValue = TransactionHistory[1];
The above code is not tested. But you can get an idea.

Categories