SQLite select statment for windows phone apps - c#

I am creating an app for windows phone for which I need to create a database connection for that i have used SQLite.
From this Link i have executed the queries:http://www.codeguru.com/csharp/.net/wp7/using-sqlite-in-your-windows-phone-application.htm
this is the code:
private void btncreate_Click(object sender, RoutedEventArgs e)
{
if (MySqlLiteDB == null)
{
MySqlLiteDB = new SQLiteConnection("MyTestDB");
MySqlLiteDB.Open();
MessageBox.Show("Connection opened Successfully!!!");
}
}
private void btnpopulate_Click(object sender, RoutedEventArgs e)
{
SQLiteCommand cmd=MySqlLiteDB.CreateCommand("Create table student(id int primary key,name text,zipcode numeric(7))");
int i = cmd.ExecuteNonQuery();
int id = 0;
for (int j = 0; j < 20; j++)
{
id++;
string name = "Name" + id;
int zipcode = 98000 + id;
cmd.CommandText = "Insert into student(id,name,zipcode) values(" + id + ",\"" + name + "\"," + zipcode + ")";
i = cmd.ExecuteNonQuery();
}
MessageBox.Show("Insert successful");
}
private void btnclear_Click(object sender, RoutedEventArgs e)
{
SQLiteCommand cmd = MySqlLiteDB.CreateCommand("drop table student");
int i = cmd.ExecuteNonQuery();
MessageBox.Show("Data Cleared successfully");
}
private void btnclose_Click(object sender, RoutedEventArgs e)
{
if (MySqlLiteDB != null)
{
MySqlLiteDB.Dispose();
MySqlLiteDB = null;
MessageBox.Show("Connection closed");
}
}
but now i need to retrieve the data from database table and bind it to a grid using select statement how can i do this?
I want to show the table data in a grid is there any way to bind the data to a grid.

Add the following function and class in your code
public class student
{
public int id {get;set;}
public string name {get;set;}
public long zipcode {get;set;}
}
SelectFromStudent()
{
string query="select id,name,zipcode from student";
List<student> studentList = SelectFromTable<student>(query);
}
List<T> SelectFromTable<T>(String statement) where T : new()
{
SQLiteCommand cmd = MySqlLiteDB.CreateCommand(statement);
var lst = cmd.ExecuteQuery<T>();
return lst.ToList<T>();
}
You can't use grid bind data in windows phone application. there is another control to do such kind of operation ListBox. you can edit Itemtemplate of ListBox. ListBox has itemsource property.

Related

Increase a variable in a loop and for each increment, apply for each new thread

How to increase a variable every time I create a new Thread and store that value? I want to do mysqlbackup in each thread for different databases, and I will get the curBytes/totalBytes completed on Class1.cs. I want to update that value into datagridview.Row[iterate].Cell[2] simultaneously between threads where iterate corresponds with value 0 for first thread, 1 for second thread and so on.
I have tried using Interlocked.Increment and lock() but they seem not to work. I don't want to use BackgroundWorker.
This is the code that I haven't done anything to change datagridIterate (the value that iterate through datagridview Rows)
Form.cs:
private void button1_Click(object sender, EventArgs e)
{
restoreUI();
}
public void restoreUI()
{
mysqlUtils msu = new mysqlUtils();
foreach(DataGridViewRow row in dataGridView1.Rows)
{
Thread t = new Thread(() =>
{
msu.Restore(row.Cells[1].Value?.ToString(), server.Text, username.Text,
pwd.Text, row.Cells[0].Value?.ToString());
}
t.Start();
}
}
Class1.cs:
namespace Utils
{
public class mysqlUtils
{
public int total;
public int cur;
public void Restore(string filename, string server, string user,
string password, string db)
{
string constring = "server=" + server + ";user=" + user +
";pwd=" + password + ";database=" + db + ";";
string file = "C:\\Users\\SQL FILES\\" + filename;
using (MySqlConnection conn = new MySqlConnection(constring))
{
using (MySqlCommand cmd = new MySqlCommand())
{
using (MySqlBackup mb = new MySqlBackup(cmd))
{
cmd.Connection = conn;
conn.Open();
mb.ImportInfo.IntervalForProgressReport = 50;
mb.ImportProgressChanged += updateProgress;
mb.ImportFromFile(file);
conn.Close();
}
}
}
}
}
public void updateProgress(object sender, ImportProgressArgs e)
{
total = (int)e.TotalBytes;
cur = (int)e.CurrentBytes;
Form4 form4 = (Form4)Application.OpenForms[0];
form4.updateProgressValue(total, cur);
}
}
How should I manage to change datagridIterate that will have value i for first thread, i+1 for the next thread and so on? I would highly appreciate if you have any support.
Here's a big hint for your code that might help you to understand what you need.
Try this:
public class Form4 : Form
{
private DataGridView dataGridView1 = new DataGridView();
private TextBox server = new TextBox();
private TextBox username = new TextBox();
private TextBox pwd = new TextBox();
private void button1_Click(object sender, EventArgs e)
{
RestoreUI();
}
public void RestoreUI()
{
MySqlUtils msu = new MySqlUtils();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
string filename = row.Cells[1].Value?.ToString();
string s = server.Text;
string user = username.Text;
string password = pwd.Text;
string db = row.Cells[0].Value?.ToString();
Thread t = new Thread(() => msu.Restore(filename, s, user, password, db, UpdateProgress));
t.Start();
}
}
public void UpdateProgress(object sender, ImportProgressArgs e)
{
this.Invoke((Action)(() =>
{
/* add your code here to update the UI */
}));
}
}
And your MySqlUtils class.
public class MySqlUtils
{
public void Restore(string filename, string server, string user, string password, string db, ImportProgressChange updateProgress)
{
string constring = "server=" + server + ";user=" + user + ";pwd=" + password + ";database=" + db + ";";
string file = "C:\\Users\\SQL FILES\\" + filename;
using (MySqlConnection conn = new MySqlConnection(constring))
{
using (MySqlCommand cmd = new MySqlCommand())
{
using (MySqlBackup mb = new MySqlBackup(cmd))
{
cmd.Connection = conn;
conn.Open();
mb.ImportInfo.IntervalForProgressReport = 50;
mb.ImportProgressChanged += updateProgress;
mb.ImportFromFile(file);
conn.Close();
}
}
}
}
}
NB: I've changed the naming conventions to standard C#.

Load image from datagridview c#

Im trying to fill a DataGridView with the value coming from my database. There is one column that has a value of a BLOB or image. Now when I'm loading it to the DataGridView it shows an error: Parameter is not valid. Can someone help me about this?
Triggering the method
private void Form1_Load(object sender, EventArgs e)
{
//load company to datagrid
string company = "SELECT * from tbl_payroll_company";
payroll.FillDataGrid(company, payroll_company_datagrid);
}
Method for filling my datagrid
public void FillDataGrid(string query,DataGridView gridview)
{
dbcon.Initialize();
if (dbcon.OpenCon() == true)
{
dt = new DataTable();
adapter = new MySqlDataAdapter(query, dbcon.con);
adapter.Fill(dt);
gridview.DataSource = dt;
dbcon.con.Close();
}
}
Here's how i saved it
private void btnCompanyUpload_Click(object sender, EventArgs e)
{
OpenFileDialog CompanyFileDialog = new OpenFileDialog();
if(CompanyFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
Image logo = Bitmap.FromFile(CompanyFileDialog.FileName);
payroll_company_logo.Image = logo;
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
private void btnCompanySave_Click(object sender, EventArgs e)
{
if(dbcon.OpenCon() == true)
{
MemoryStream stream = new MemoryStream();
if (payroll_company_logo.Image != null)
{
payroll_company_logo.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
byte[] logo = stream.ToArray();
string[] column_name = {"payroll_company_logo"};
string table = "tbl_payroll_company";
string[] column_value = {logo.ToString()};
dbcon.Insert(table,column_name,column_value);
}
}
public void Insert(string table,string[] columns,string[] values)
{
this.Initialize();
con.Open();
MySqlCommand cmd = new MySqlCommand("INSERT INTO " + table + "(" + string.Join(",", columns) + ") VALUES('" + string.Join("','", values) + "')", con);
int check = cmd.ExecuteNonQuery();
con.Close();
}
ERROR

SQL Server : cannot understand why when I create one record in table A, two records are created in table B

I am creating a record using C# in a table named units allocation. Whenever I create a record in this table I need to have fields from students table to create records in the grades table. Currently, its working but for every record I create, I get two records in the grades table.
However, the students table has only one record.
I can't seem to figure out the problem but I am suspecting it could be the sql statement. Please checkout for me.
private void gridControl4_EmbeddedNavigator_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
{
if (e.Button.ButtonType == DevExpress.XtraEditors.NavigatorButtonType.Remove)
{
GridView view = gridControl4.FocusedView as GridView;
view.DeleteRow(view.FocusedRowHandle);
e.Handled = true;
}
if (e.Button.ButtonType == DevExpress.XtraEditors.NavigatorButtonType.Append)
{
gridView4.UpdateCurrentRow();
e.Handled = true;
}
/*if (e.Button.ButtonType == DevExpress.XtraEditors.NavigatorButtonType.EndEdit)
{
if (MessageBox.Show("Do you want to commit changes to the current record?", "Confirm commit",
MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) != DialogResult.No)
{
gridView4.CloseEditor();
gridView4.UpdateCurrentRow();
}
}*/
}
object val1;
object val2;
object val3;
private void gridView4_CellValueChanged_1(object sender, CellValueChangedEventArgs e)
{
this.units_allocationTableAdapter7.Update(this.jmsDataSet22.units_allocation);
string connetionString = null;
connetionString = "Server=localhost\\SQLEXPRESS;Integrated security=SSPI;database=jms";
using (SqlConnection con = new SqlConnection(connetionString))
{
int rowHandle = e.RowHandle;
val1 = gridView4.GetRowCellValue(rowHandle, gridView4.Columns[5]);
val2 = gridView4.GetRowCellValue(rowHandle, gridView4.Columns[6]);
val3 = gridView4.GetRowCellValue(rowHandle, gridView4.Columns[10]);
string sql2 = "INSERT INTO grades (registration_no,first_name,middle_name,surname) (SELECT registration_no, first_name, middle_name, surname FROM students WHERE class_code='" + val3 + "')";
con.Open();
using (SqlCommand cmd = new SqlCommand(sql2, con))
{
cmd.ExecuteNonQuery();
con.Close();
}
}
this.gradesTableAdapter1.Fill(this.jmsDataSet24.grades);
}
private void gridView4_RowUpdated(object sender, RowObjectEventArgs e)
{
}
private void gridView4_RowDeleted_1(object sender, DevExpress.Data.RowDeletedEventArgs e)
{
this.units_allocationTableAdapter7.Update(this.jmsDataSet22.units_allocation);
}

How to delete a row from gridview on button click after the row's checkbox is selected

I have a DataGridView created in C# windows forms and checkboxColumn added to it. The DataGridView is populated with other columns like Sno, AccountNo, Name, Salary (Sno is identitycolumn and primarykey).
I want to delete a row (using stored procedure) by selecting the checkbox and on button click which is out side DataGridView. Error at "FindControl".
Stored Procedure:
Create Procedure uspDeleteSelectedRow
As
Delete from EmpDetails where Sno=Sno
Go
private void btnDelete_Click(object sender, EventArgs e)
{
//Create String Collection to store IDs of
//records to be deleted
StringCollection idCollection = new StringCollection();
string strID = string.Empty;
//Loop through GridView rows to find checked rows
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
CheckBox chkDelete = (CheckBox)dataGridView1.Rows[i].
Cells[0].FindControl("chkSelect");
if (chkDelete != null)
{
if (chkDelete.Checked)
{
strID = dataGridView1.Rows[i].Cells[1].ToString();
idCollection.Add(strID);
}
}
}
if (idCollection.Count > 0)
{
//Call the method to Delete records
DeleteMultipleRecords(idCollection);
// rebind the GridView
dataGridView1.DataBind();
}
else
{
lblMessage.Text = "Please select any row to delete";
}
}
private void DeleteMultipleRecords(StringCollection idCollection)
{
//Create sql Connection and Sql Command
SqlConnection con = new SqlConnection(Helper.ConnectionString);
SqlCommand cmd = new SqlCommand();
string IDs = "";
foreach (string id in idCollection)
{
IDs += id.ToString() + ",";
}
try
{
string test = IDs.Substring
(0, IDs.LastIndexOf(","));
string sql = "Delete from EmpDetails" + " WHERE ID in (" + test + ")";
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
string errorMsg = "Error in Deletion";
errorMsg += ex.Message;
throw new Exception(errorMsg);
}
finally
{
con.Close();
}
}
Let say this is your stored procedure:
ALTER PROCEDURE [dbo].[sp_ToDeleteEmpDetails] #Sno int
/*
(
#parameter1 int = 5,
#parameter2 datatype OUTPUT
)
*/
AS
DELETE FROM EmpDetails
WHERE Sno = Sno
RETURN
You don't need a StringCollection to delete or call the stored procedure.
private void btnDelete_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow item in dataGridView1.Rows)
{
bool IsBool = false;
if (bool.TryParse(item.Cells[1].EditedFormattedValue.ToString(), out IsBool)) //<--Where: The ColumnIndex of the DataGridViewCheckBoxCell
{
using (SqlConnection con = new SqlConnection(Helper.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("sp_ToDeleteEmpDetails", con))
{
try {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#sno", SqlDbType.Int).Value = item.Cells[0].EditedFormattedValue.ToString(); //<--Where: The ColumnIndex of the Primary key from your DataGridView
dataGridView1.Rows.RemoveAt(item.Cells[0].RowIndex);
con.Open();
cmd.ExecuteNonQuery();
} catch (Exception) {
throw;
}
finally
{
con.Close();
}
}
}
}
}
}
Please let me know if you have some encountered problem from my given answer.
Try this solution. In my code I have class and pass a list of it to gridview as my datasource.
//Class
public class User
{
public bool Selected { get; set; }
public string UserName { get; set; }
}
//Create a list and bind to the data grid view
private void Form1_Load(object sender, EventArgs e)
{
var users = new List<User> { new User { UserName = "Jobert", Selected = false }, new User { UserName = "John", Selected = true }, new User { UserName = "Leah", Selected = true }, new User { UserName = "Anna", Selected = false } };
dataGridView1.DataSource = users;
}
//On delete
private void btnDelete_Click(object sender, EventArgs e)
{
//get data back from the source
var source = dataGridView1.DataSource as List<User>;
var selectedItems = source.Where(x => x.Selected).ToList();
foreach (var item in selectedItems)
{
//perform the delete
}
}

Use List to populate labels C#

I'm creating a device application in VS 2005.
I created a List called "info" and want to populate labels on my form with the values from the List. This is my code:
public List<String> info = new List<String>();
int i = 0;
private void populateinfo()
{
conn.Open();
string query;
query = "select distinct dp.current_location_code,dci.dest_location_code,dps.order_no,dps.company_id_no,dps.no_of_full_cartons,dps.dc_grv_id_no,s.sku_code from dc_pallet_stock dps, dc_pallet dp,sku s , purch_order_carton_sku pocs , dc_crane_instruc dci where dp.pallet_id_no = dps.pallet_id_no and dps.order_no = pocs.order_no and dps.company_id_no = pocs.company_id_no and dps.carton_code = pocs.carton_code and s.sku_id_no = pocs.sku_id_no and s.company_id_no = dps.company_id_no and dp.pallet_id_no = '" + palletId + "' and dci.pallet_id_no(+) = dps.pallet_id_no";
OracleCommand cmd = new OracleCommand(query, conn);
OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
this.info.Add(dr["order_no"].ToString());
}
dr.Close();
conn.Close();
}
private void frmInfo_Load(object sender, EventArgs e)
{
populateinfo();
lbl3.Text = this.info[++i];
{
Im getting error at lbl3.Text = this.info[++i];
Specified argument was out of the range of valid values. Parameter name: index.
This is how I'm testing it at the moment, but at the end I want all the columns in my query to be shown in separate labels, how would I do this. Or is there a better way of doing it? Gridview is no option.
Thanks in advance.
What I probably would do would to create either an Array of your labels or a List of your labels iterate through it. Here is an example dynamically creating your labels and adding them to your form.
public List<String> info = new List<String>();
public List<Label> labels = new List<Label>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
populateinfo();
for (int i = 0; i < info.Count; i++)
{
labels.Add ( new Label(){Name="lbl"+i+1, Text=info[i],
Font = new Font("Arial",8),
ForeColor= Color.Blue});
}
placelabels();
}
private void placelabels()
{
int topvalue = 0;
foreach (Label item in labels)
{
item.Left = 0;
item.Top = topvalue;
this.Controls.Add(item);
topvalue += 20;
}
}
And a method adding your existing labels to a List
public List<String> info = new List<String>();
public List<Label> labels = new List<Label>();
public Form1()
{
InitializeComponent();
labels.Add(label1);
labels.Add(label2);
labels.Add(label3);
labels.Add(label4);
labels.Add(label5);
}
private void Form1_Load(object sender, EventArgs e)
{
populateinfo();
if (labels.Count > info.Count)
{
for (int i = 0; i < info.Count; i++)
{
labels[i].Text = info[i];
}
}
else
{
for (int i = 0; i < labels.Count; i++)
{
labels[i].Text = info[i];
}
}
}
try to use like this.
...
while (dr.Read())
{
lbl3.Text += dr["order_no"].ToString() + "\n";
}
...
palletId in my select query was incorrect. Please see constructor:
public List<String> info = new List<String>();
int i = 0;
public frmInfo(string palletId)
{
InitializeComponent();
this.palletId = palletId;
}
private void populateinfo()
{
conn.Open();
string query;
query = "select distinct dp.current_location_code,dci.dest_location_code,dps.order_no,dps.company_id_no,dps.no_of_full_cartons,dps.dc_grv_id_no,s.sku_code from dc_pallet_stock dps, dc_pallet dp,sku s , purch_order_carton_sku pocs , dc_crane_instruc dci where dp.pallet_id_no = dps.pallet_id_no and dps.order_no = pocs.order_no and dps.company_id_no = pocs.company_id_no and dps.carton_code = pocs.carton_code and s.sku_id_no = pocs.sku_id_no and s.company_id_no = dps.company_id_no and dp.pallet_id_no = '" + palletId + "' and dci.pallet_id_no(+) = dps.pallet_id_no";
OracleCommand cmd = new OracleCommand(query, conn);
OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
this.info.Add(dr["order_no"].ToString());
}
dr.Close();
conn.Close();
}
private void frmInfo_Load(object sender, EventArgs e)
{
populateinfo();
lbl3.Text = this.info[++i];
{

Categories

Resources