Retrieve data for List box - c#

I have inserted data from list box. I want to retrieve data for specific skill set in gridview.
for example if i select android in dropdownlist and press button it must give people who have android skill set only.
Does any body know how to do this
private string GetConnectionString()
{
//Where DBConnection is the connetion string that was set up in the web config file
return System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
}
private void InsertRecords(StringCollection sc)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
StringBuilder sb = new StringBuilder(string.Empty);
foreach (string item in sc)
{
const string sqlStatement = "INSERT INTO Table1 (Employees) VALUES";
sb.AppendFormat("{0}('{1}'); ", sqlStatement, item);
}
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sb.ToString(), conn);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
StringCollection sc = new StringCollection();
foreach (ListItem item in ListBox1.Items)
{
if (item.Selected)
{
sc.Add(item.Text);
}
}
InsertRecords(sc);
}

Yes you can do this using where clause like this
string query="select * from Employees where skill= '" +yourvalue+ "'";

have your gridview datasource configured, during configuration whereever you have your SkillsetID or whateever that is, FOR THAT, use the "WHERE" clause which say that SkillSetID is bound to the "control" with ID lstBasePackageAsset with "selected value" or just "selected" i.e
gridview1.skillsetID = lstBasePackageAsset.selectedvalue ;
You will be done.
And please next time, or even now, let people know if it is VisualStudio query or any other developement source query. It is more easier in VS but require more programming code in command line (if you are doing that)
string query="select * from Employees where skill= '" +yourvalue+ "'";

Related

Deleting a row in a database from datagridview C#

I'm trying to remove an entry from both the datagridview and the database. I got it so it removes the row from the data grid view but it fails to delete it also from the database. Here is my code I have in place:
private void listBtn_Click(object sender, EventArgs e)
{
MySqlDataAdapter mysqldatadapter = new MySqlDataAdapter("select id, username from members ORDER BY id", new MySqlConnection(conn.connectionString));
mysqldatadapter.Fill(ds);
dataGridView.DataSource = ds.Tables[0];
listBtn.Enabled = false;
}
private void btnDelete_Click(object sender, EventArgs e)
{
using (MySqlConnection dbConn = new MySqlConnection(conn.connectionString))
{
dbConn.Open();
for (int i = 0; i < dataGridView.Rows.Count; i++)
{
DataGridViewRow row = dataGridView.Rows[i];
if (row.Selected == true)
{
dataGridView.Rows.RemoveAt(i);
MySqlCommand cmd = dbConn.CreateCommand();
cmd.CommandText = "DELETE FROM members WHERE id = " + i;
try
{
cmd.ExecuteNonQuery();
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
}
}
}
dbConn.Close();
}
}
I'm at a loss concerning this, any help would be appreciated.
Thanks!
Update - Is there a way to grab the value of individual cells to pass to the mysql command? For instance, grabbing the id?
Your values for i probably don't match the id fields in the member table.
You probably need to change this line:
cmd.CommandText = "DELETE FROM members WHERE id = " + i;
to
cmd.CommandText = "DELETE FROM members WHERE id = " + row.cells[id.Index].ToString();

Mass update mysql table

I have a list of 1933 user names that have to be set to deleted in a mysql table (change the deleted field from 0 to 1). I'm pasting a comma delimited list (username, realname) in a list box and using a foreach statement to send each username, realname group to an update command in a static class. When I run it, I don't get any errors but none of the users rows are updated. I'm doing something wrong but I'm not sure what the issue is. Please review my code below and let me know if you find something wrong that I'm not seeing.
private void button1_Click(object sender, EventArgs e)
{
int i = 0;
try
{
if (listBox1.Items.Count > 0)
{
foreach (string s in listBox1.Items)
{
Cursor.Current = Cursors.WaitCursor;
string[] sname = s.Split(',');
Data.RemoveUser(sname[0].ToString(), sname[1].ToString());
i++;
label3.Text = i.ToString();
}
}
else
MessageBox.Show("No user names found. Please paste a list of names to be deleted.");
Cursor.Current = Cursors.Default;
MessageBox.Show(i.ToString() + " users set to deleted.");
}
catch (Exception ex)
{
throw ex;
}
}
public static void RemoveUser(string UserName, string FullName)
{
MySqlConnection conn = new MySqlConnection(constr);
try
{
conn.Open();
string qry = "Update host_user set deleted = 1 where username = #username and name = #fname";
MySqlCommand cmd = new MySqlCommand(qry, conn);
cmd.Parameters.AddWithValue("#username", UserName);
cmd.Parameters.AddWithValue("#fname", FullName);
cmd.ExecuteNonQuery();
conn.Close();
}
catch (MySqlException e)
{
if (conn != null) conn.Close();
throw e;
}
}
When you are doing:
string[] sname = s.Split(',');
Do you end up with spaces on either side of you first name and last name? If your input was like:
"John, Doe"
You would end up search on "John" & " Doe".
If this is the case, call .Trim() on those strings before passing passing them into RemoveUser().

Refreshing the combobox after inserting data in mysql c#

Hello so i want to refresh my combobox after i add or delete data from it now if i add data it doesnt get refreshed i have to rerun the program to see the changes but i want to get it refresh in the time i add the data..
the code when i add data:
private void button5_Click(object sender, EventArgs e)
{
MySqlConnection dataConnection = new MySqlConnection();
dataConnection.ConnectionString = "datasource=localhost;port=3306;username=root;password=";
dataConnection.Open();
MySqlTransaction transakcija = dataConnection.BeginTransaction();
MySqlCommand dataCommand = new MySqlCommand();
dataCommand.Connection = dataConnection;
dataCommand.Transaction = transakcija;
try
{
dataCommand.CommandText = "Insert INTO filmi.film (film) VALUES ('" + this.tB_Dodaj.Text + "')";
dataCommand.CommandType = CommandType.Text;
dataCommand.ExecuteNonQuery();
transakcija.Commit();
MessageBox.Show("You added a new movie!");
}
catch (Exception eks)
{
transakcija.Rollback();
MessageBox.Show("Movie couldnt be added!!\n" + eks.Message);
}
finally
{
dataCommand.Connection.Close();
}
}
and with each insert the data gets displayed in the combobox but only when i rerun the program
this is how i fill combobox:
void Fillcombo()
{
string constring = "datasource=localhost;port=3306;username=root;password=";
string Query = "SELECT * FROM filmi.film ;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string sName = myReader.GetString("film");
comboBox1.Items.Add(sName);
comboBox2.Items.Add(sName);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
i have to rerun the program to see the changes but i want to get it
refresh in the time i add the data..
I suspect that you are calling the Fillcombo() method in Form_Load event handler.
if you want to update the combobox for every insert and delete operations in your table you need to call Fillcombo() immediatly after executing the command.
Try This:
int status = dataCommand.ExecuteNonQuery();
transakcija.Commit();
if(status > 0)
{
Fillcombo();
MessageBox.Show("You added a new movie!");
}
in your FillCombo clear the items before adding the new items to remove the duplicates.
comboBox1.Items.Clear(); //add this statetement before adding items
comboBox2.Items.Clear(); //add this statetement before adding items
while (myReader.Read())
{
string sName = myReader.GetString("film");
comboBox1.Items.Add(sName);
comboBox2.Items.Add(sName);
}
ADO.NET object works in a disconnected state, so, adding a record to your datatable doesn't automatically shows up in your combo. You need to call again FillCombo, (clearing the items already in combos, going again to the database to retrieve every record again, adding them to your comboboxes) or just simply adding the film to your already filled combos as a single item
Also pay attention to Sql Injection (use always a parameterized query)
private void button5_Click(object sender, EventArgs e)
{
string conString = "datasource=localhost;port=3306;username=root;password=";
string cmdText = "Insert INTO filmi.film (film) VALUES (#film)";
using(MySqlConnection dataConnection = new MySqlConnection(conString))
using(MySqlCommand dataCommand = new MySqlCommand(cmdText, dataConnection))
{
try
{
dataConnection.Open();
dataCommand.Parameters.AddWithValue("#film", this.tB_Dodaj.Text);
// If ExecuteNonQuery returns a value > 0 then your record has been inserted
// Just add the name of the film to the two combos
if(dataCommand.ExecuteNonQuery() > 0)
{
MessageBox.Show("You added a new movie!");
comboBox1.Items.Add(this.tB_Dodaj.Text);
comboBox2.Items.Add(this.tB_Dodaj.Text);
}
}
catch(Exception ex)
{
MessageBox.Show("Fail to add a new movie! " + ex.Message);
}
}
}
As a last note, watch carefully your fillcombo method. You don't close and dispose the connection.

Delete record from MDF database

I want to create simple application in C#. It should be windowsForms app, with service-based database added to project. In this I want to make table (ID, name, second name) and in program show name into listBox. Current name selected in listBox will be deleted (row will be deleted)
Can anyone help me how to do it? I have try with dataset, this is working, but after I close app and run it again, table is full with data again.
For saving records into database and loading them in a listbox you can see..
save-data-to-database-then-load-data-to-listbox
Now,for deleting a record from a listbox you can code like this..
protected void removeButton_Click(object sender, EventArgs e)
{
if (ListBox1.SelectedItem.Text == null)
{
MessageBox.Show("Please select an item for deletion.");
}
else
{
for (int i = 0; i <= ListBox1.Items.Count - 1; i++)
{
if (ListBox1.Items[i].Selected)
{
DeleteRecord(ListBox1.Items[i].Value.ToString());
}
}
string remove = ListBox1.SelectedItem.Text;
ListBox1.Items.Remove(remove);
}
}
For deleting that record also from database use like this..
private void DeleteRecord(string ID)
{
SqlConnection connection = new SqlConnection("YOUR CONNECTION STRING");
string sqlStatement = "DELETE FROM Table1 WHERE Id = #Id";
try
{
connection.Open();
SqlCommand cmd = new SqlCommand(sqlStatement, connection);
cmd.Parameters.AddWithValue("#Id", ID);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Deletion Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
connection.Close();
}
}

How to delete from database selected item in ListView in C#

I am using Microsoft SQL Server and Visual Studio-C# 2010 Ultimate.
I have a ListView and some items in it. I want to delete an item when I selected it and I clicked the button but I could not write the SqlCommandtext and I could not find the select event for ListView.
Deleting selected data from database using listview c#
private void btnlvdeleterow_Click(object sender, EventArgs e)
{
foreach (int i in Listview2.SelectedIndices)
{
string test = Listview2.Items[i].Text;
Listview2.Items.Remove(Listview2.Items[i]);
SQLiteCommand conn = new SQLiteCommand();
conn.Connection = DbClass1.GetConnection();
string del = "delete from UserData where UserName='" + test + "'";
int result=dbclass1.ExecuteAndReturn(del);
}
}
There is a SelectedIndex property available with the ListView. When you click the button, pass this index and then your Sql query will be something like
delete from Products where ProductID = 'obj.ID' where obj is obtained from listView.SelectedIndex
protected void listview1_ItemDeleting(object sender, ListViewDeleteEventArgs e)
{
//This retrieves the selected row
ListViewItem item= listview1.Items [e.ItemIndex];
// Fetch the control for ProductId using findControl
int productId=int.Parse((item.Findcontrol("ProductID") as TextBox).Text);
//then use this column value in your sqlcommand
using( SqlCommand cmd = new SqlCommand
("delete from Products where ProductID=#ProductId", connection ))
{
command.Parameters.Add(new SqlParameter("ProductId", productId));
//Then execute the query
}
}
try
{
for (int j = 0; j <= listView2.Items.Count - 1; j++)
{
string test = listView2.SelectedItems[j].SubItems[1].Text;
string MyConnection2 = "datasource=localhost;port=3306;username=root;password=root";
string Query = "delete from TABLE_NAME where COL_NAME='" + test + "'";
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
MySqlDataReader MyReader2;
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader();
while (MyReader2.Read())
{
}
MyConn2.Close();
MessageBox.Show("Data Deleted");
// txtCustomerName.Text = test;
//listView2.Items.Remove(listView2.Items[i]);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
The Event you are looking for should be ListView.ItemSelectionChanged
where the eventArgs contains the selected Items

Categories