executing function/method in button click event - c#

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

Related

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;}

Search button in DataGridView with textboxchanged

I want to do search button in DataGridView. I read my data with this code:
private void button1_Click_1(object sender, EventArgs e)
{
FileStream f1 = new FileStream("zapis.dat", FileMode.Open);
BinaryReader br = new BinaryReader(f1);
int а = 0;
while (f1.Position < f1.Length)
{
string data = br.ReadString();
string sing = br.ReadString();
string avtor = br.ReadString();
string zagl = br.ReadString();
string janr = br.ReadString();
string ezik = br.ReadString();
dataGridView1.Rows.Add(++а, ezik, zagl, avtor, janr, sing, data);
}
f1.Close();
}
I trying to do button with code:
private void textBox1_TextChanged(object sender, EventArgs e)
if (string.IsNullOrEmpty(textBox1.Text))
{
(dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Empty;
}
else
{
(dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("Name='{0}'", textBox1.Text);
}
}
but when I started, I get error:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
(... as System.Data.DataTable) returned null.
on:
else
{
(dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("Name='{0}'", textBox1.Text);
How I can fix it?
You are not using DataTable as datasource for DataGridView.
Use a class to represent your data, then you will be able to do the job without "heavy" DataTable.
public class Item
{
public string Data { get; set; }
public string Sing { get; set; }
public string Avtor { get; set; }
// and so on ...
}
// Save data into private class member
private List<Item> _loadedData = new List<Item>();
private void button1_Click_1(object sender, EventArgs e)
{
using (var stream = new FileStream("zapis.dat", FileMode.Open))
using (var reader = new BinaryReader(stream))
{
var data = new List<Item>();
while (stream.Position < stream.length)
{
var item = new Item
{
Data = reader.ReadString(),
Sing = reader.ReadString(),
Avtor = reader.ReadString()
};
data.Add(item)
}
// update private member with newly loaded data
_loadedData = data;
}
// Bind loaded data to the DataGridView
datagridview1.DataSource = _loadedData;
}
Filtering can be done with simple Where method for _loadedData collection.
private void textBox1_TextChanged(object sender, EventArgs e)
{
var filtered = _loadedData.Select(item => item);
if (string.IsNullOrEmpty(textBox1.Text) == false)
{
filtered = filtered.Where(item => item.Avtor == textBox1.Text);
}
datagridview1.DataSource = filtered.ToList();
}

How to Add a value from combox to data grid view in C#

I have data in combo box retrieved from database.
How do I add that data to Data Grid View when value are selected from combo box?
SqlConnection conn = new SqlConnection(conStr);
string query = "select * from products";
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
comboBox3.Items.Add(rdr[0]+"-\t"+rdr[1]+"-"+"Exp Date\t"+rdr[4]);
}
conn.Close();
above is my code that retrieve data to combo box,
There are two ways to solve your problem according to following setups
If you just want to add only single row for your dataGridView then you only have to use the concept of list according to following Method(1).
But If you want to add more rows upon select from ComboBox then you would use DataTable Method(2). Note that DataTable also include primaryKey for your productID Column in GridView that selected from ComboBox.
If you want to remove Primary Key Comment the code of primary key in Method(2).
Method(1):
public class GridviewData
{
public string ProductId{set;get;}
public string ProductName { set; get; }
public string ExpireDate { set; get; }
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedItem = comboBox1.SelectedItem.ToString();
List<string> dataList = selectedItem.Split('-').ToList();
GridviewData data = new GridviewData();
data.ProductId = dataList[0];
data.ProductName = dataList[1];
data.ExpireDate = dataList[2];
List<GridviewData> gridviewList = new List<GridviewData>();
gridviewList.Add(data);
dataGridView1.DataSource = gridviewList;
}
}
Method(2):
public partial class Form1 : Form
{
DataTable dt = new DataTable();
public Form1()
{
InitializeComponent();
DataColumn productID = new DataColumn();
productID.ColumnName = "Product ID";
dt.Columns.Add(productID);
dt.Columns.Add("Product Name");
dt.Columns.Add("Expire Date");
dt.PrimaryKey = new DataColumn[] {productID };//if you want to set primary key for dataTable upon productID
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
string selectedItem = comboBox1.SelectedItem.ToString();
List<string> data = selectedItem.Split('-').ToList();
dt.Rows.Add(new object[] { data[0], data[1], data[2] });
dataGridView1.DataSource = dt;
}
catch(Exception er)
{
MessageBox.Show(er.Message);
}
}
}
If you want to remove PrimaryKey then comment following code,
//dt.PrimaryKey = new DataColumn[] {productID };
Stay blessed
So you should save records on a list, array etc for example:
List<string> LstProductos = new List<string>;
Then
while (rdr.Read())
{
LstProductos.Add(rdr[0]+"-\t"+rdr[1]+"-"+"Exp Date\t"+rdr[4])
}
For load Combobox:
foreach(string str in LstProductos)
{
ComboBox.items.add(str);
}
Finally on your SelectedIndexChanged event of your combobox:
private void comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
string YourItem = comboBox1.Text;
//If you only want to add selected item
DataGridView.Add(YourItem);
//or add all
foreach (string str in LstProductos)
{
DataGridView.Rows.Add(str);
}
}

c# thread/query executing twice

I'm working on some code that executes MDX queries against sql server analysis service. The MDX query is being executed twice on the same thread and I have no idea why. The query should only execute once
Below is some of the code. can anyone help please.
private void Start_QueryWorkers()
{
foreach (QueryThread th in _QueryWorkers)
{
SSASQuery q = new SSASQuery();
q.QueryText = "SELECT NON EMPTY { [Measures].[count] } ON COLUMNS FROM [cube]";
q.queryThread = th;
th.WorkerThread.RunWorkerAsync(q);
}
}
private void QueryWorkerThread_DoWork(object sender, DoWorkEventArgs e)
{
SSASQuery q = e.Argument as SSASQuery;
OleDbCommand cmd = new OleDbCommand(q.QueryText, q.queryThread.conn);
OleDbDataReader rdr = cmd.ExecuteReader();
rdr.Close();
}
private void btnStartTest_Click(object sender, EventArgs e)
{
string strConnString = "Provider=MSOLAP;Data Source=SRV001" + ";Initial Catalog=Cube_2015" + ";";
_QueryWorkers.Clear();
{
QueryThread thread = new QueryThread(strConnString);
thread.WorkerThread = new BackgroundWorker();
thread.WorkerThread.DoWork += new DoWorkEventHandler(this.QueryWorkerThread_DoWork);
_QueryWorkers.Add(thread);
}
Start_QueryWorkers();
}
}
class SSASQuery
{
public string QueryText { get; set; }
public QueryThread queryThread { get; set; }
}
class QueryThread
{
public QueryThread(string connString)
{
this.connString = connString;
conn = new OleDbConnection(connString);
conn.Open();
queryList = new SortedList();
}
public SortedList queryList { get; set; }
public string threadName { get; set; }
public string connString { get; set; }
public OleDbConnection conn;
public BackgroundWorker WorkerThread { get; set; }
}
}
solved. code was ok, it was a problem in the connection string execting the query twice

class that gets a value from database [closed]

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;
}

Categories