I'm struggling to change a variable from a database into a usable Int so I can compare against the database to delete rows.
Here's the code I'm using:
private void EditEmployee_Load(object sender, EventArgs e)
{
DataTable table = new DataTable(); //creates a Table to store the data before populating the ComboBox
string connstring = #"Provider = Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\HoliPlanData.accdb;Persist Security Info=False";
try
{
using (OleDbConnection conn = new OleDbConnection(connstring))
{
conn.Open();
string query = "SELECT PayrollNo, (FirstName + ' ' + LastName) AS NAME FROM [Employee]";
OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn);
adapter.Fill(table);
DropBoxEmp.DataSource = table;
DropBoxEmp.DisplayMember = "NAME";
DropBoxEmp.ValueMember = "PayrollNo";
string BadNumber = DropBoxEmp.ValueMember;
int GoodNumber = Int32.Parse(BadNumber);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
The problem is that the string BadNumber is set to the string "PayrollNo", instead of a string version of the Int that the Datatable stores PayrollNo as. When I set the DisplayMember to "PayrollNo", the combobox displays 1 and 2 and so on, as the Int's selected in the SELECT query.
Why does BadNumber take the literal assigned to DropBoxEmp.ValueMember instead of the numbers? Any help would be gratefully received.
You want DropBoxEmp.SelectedItem, not ValueMember. You are misunderstanding what the ValueMember property is. It tells the combo box which field in its binding to use as the backing value.
To unbox, do this:
var theItem = DropBoxEmp.SelectedItem as DataRowView;
MessageBox.Show(theItem[0].ToString());
-- as an aside, the data adapter will open the connection so you don't need to do that.
Try using the column name and the row index to get the value:
if(table.Rows.Count==1) // if it's supposed to be unique
{
int GoodNumber = Int32.Parse(table.Rows[0]["PayrollNo"].ToString());
}
else
{
//Show some error
}
Related
I have an Access database that has name ID-s in a column and I filled up the first column with those ID-s (38, 51, 88) and what I want to do is based on those ID-s I want to fill up the last selected column with some other data that are in the Access database but in another table.
For example, ID 38 would give me a price or a name in that row.
I tried it a lot of times but couldn't find a solution and I don't know If I have to use SQL for this or something else.
I got the needed SQL code but I don't know how to use it for the datagridview.
I have used something like that to fill up combo boxes like this:
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = "the connection string";
connection.Open();
string query2 = "SELECT Name From Names";
command.CommandText = query2;
OleDbDataReader reader2 = command.ExecuteReader();
while (reader2.Read())
{
Combobox1.Items.Add(reader2["Name"].ToString());
}
connection.Close();
And now I think I should make an if statement where it checks if the 38 ID is in the DataGridView, then fill the other cell with the value in the same row of the Access table.
Do you want to populate the datagridview with the corresponding Price and Name that from another table?
Here is a demo you can refer to.
private void btnSetPriceName_Click(object sender, EventArgs e)
{
string constr = #"connection string";
// create sql string
StringBuilder strSQL = new StringBuilder();
strSQL.Append("select Price, Name from PriceName where ");
for(int i = 0;i< dataGridView1.Rows.Count - 1;i++)
{
// get Id from string, like "38/1/R"
string Id = dataGridView1.Rows[i].Cells[0].Value.ToString().Split('/')[0];
if (i == 0)
strSQL.Append("Id = " + Id);
else
strSQL.Append("or Id = " + Id);
}
using (OleDbConnection conn = new OleDbConnection(constr))
{
OleDbCommand cmd = new OleDbCommand (strSQL.ToString(), conn);
conn.Open();
try
{
OleDbDataReader reader = cmd.ExecuteReader();
if (reader != null && reader.HasRows)
{
int rowindex = 0;
while (reader.Read())
{
// Set Price/Name column value
dataGridView1.Rows[rowindex].Cells["Price"].Value = reader[0].ToString().Trim();
dataGridView1.Rows[rowindex].Cells["Name"].Value = reader[1].ToString().Trim();
rowindex++;
}
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine("\nError:\n{0}", ex.Message);
}
}
}
I'm trying to get all the data from a column in the database. I found how to read the data from a specific column, but it shows only the first value.
Here's some of my code. Any idea how to read and show the rest data from the column?
public partial class main : Form
{
//Connect database
String connectionstring;
SqlConnection connection;
public main()
{
InitializeComponent();
//Connect database
connectionstring = ConfigurationManager.ConnectionStrings["Internet_Recovery.Properties.Settings.customerConnectionString"].ConnectionString;
Run();
}
private void Run()
{
using (connection = new SqlConnection(connectionstring))
//Select ip values from IP_table
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT Ip FROM IP_table ", connection))
{
DataTable iptable = new DataTable();
//Read ip value and add it in the listbox1
adapter.Fill(iptable);
listBox1.DataSource = iptable;
listBox1.ValueMember = "Ip";
listBox1.DisplayMember = "Id";
String num;
num = listBox1.SelectedValue.ToString();
you can do it like this :
DataSet data = new DataSet();
String num;
using (SqlConnection connection = new SqlConnection(connectionstring))
{
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT Ip FROM IP_table", connection))
{
connection.Open();
adapter.Fill(data);
listBox1.DataSource = data.Tables[0];
listBox1.DisplayMember = "Ip";
}
}
num = listBox1.SelectedValue.ToString();
First, your data doesn't have and Id field which you're trying to bind the DisplayMember to. Change your query to
SELECT Id, Ip FROM IP_table
Also you seem to be swapping the DisplayMember and ValueMember. They should be:
listBox1.ValueMember = "Id";
listBox1.DisplayMember = "Ip";
This works and displays all data from the Ip column in the list. It seems that you want to display the data from the other columns too. The ListBox control is not the best for that and you should consider using a GridView control instead. However, sometimes we don't care to display the data in grid format and all we care about is displaying it as a concatenated string in each item (e.g. firstname + " " lastname). If that's your case, you can either concatenate the columns in the query or in the code. Let's say you have the following columns in your table:
Id (e.g. 1)
Ip (e.g. 111.111.111)
Location (e.g. Virginia)
Provider (e.g. AT&T)
And let's assume you want to display them like this 111.111.111 AT&T (Virginia), then you can change your query to:
SELECT Id, Ip + ' ' + Provider + ' (' + Location + ')' AS Description FROM IP_table
And now you can change your binding properties to:
listBox1.ValueMember = "Id";
listBox1.DisplayMember = "Description";
private void DeleteClient_Load(object sender, EventArgs e)
{
try
{
connection = new SqlConnection(new DatabaseConnection().cnnString.ToString());
connection.Open();
}
catch (Exception exp)
{
MessageBox.Show(exp.Message, "Could not establish connection to the database.", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
cmd = new SqlCommand(new DatabaseAdd().addToComboBoxSE.ToString(), connection);
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach(DataRow dr in dt.Rows)
{
comboBox1.Items.Add(dr["Id"] + ". " + dr["FirstName"] + " " + dr["Surname"]);
}
connection.Close();
}
Here i am adding items to a comboBox from a database. I am adding the ID(int), FirstName(varchar) and Surname(varchar) to each item for each row in the database.
My question is, how do i go about deleting a row from the database depending on a list item i have selected within the comboBox? I am able to do it when i just add the ID(int) to the comboBox but since i need the id, firstname and surname, i am unable to retrieve the ID from whatever list option i have selected.
Any help is appreciated. Thank you.
You need to create an instance of ComboBoxItem class and set its Value property to the id you want, then add it to your combobox.
The Class ComboBoxItem.cs:
public class ComboBoxItem
{
public string Text { get; set; }
public object Value { get; set; }
public override string ToString()
{
return Text;
}
}
Inside your foreach loop should be:
ComboBoxItem itm = new ComboBoxItem();
itm.Value = dr["Id"];
itm.Text = dr["Id"] + ". " + dr["FirstName"] + " " + dr["Surname"];
ComboBox1.Items.Add(itm);
You can get the selected item's id like this:
String selectedId = ((ComboBoxItem)(ComboBox1.SelectedItem)).Value.ToString();
Hope it helps.
Assuming that the Id is a numeric field, what you need to do is to split your string and extract the value of ID from the list. Since the format of the item is identical for all items, we can use the ". " as the separator string.
So, you can write something like this:
var str = selectedItem; // this is the value of selected item from the combo box and it's type is string. Example: "123. John Doe"
int ID = 0;
var str = selectedItem.Trim(); // this is the value of selected item from the combo box and it's type is string
var index = selectedItem.IndexOf(". ");
if (index > 1)
{
ID = Int32.Parse(selectedItem.Substring(0, index ) );
}
I was not sure
if you're asking to remove a row from the ComboBox once selected then
or delete from the db
This handles both, remove from Combo or delete from DB RowDeleter(string cmbName = "", bool deleteFromComboxBox )
Edit 1 updated the code based on comment:
//added optional parameter to pass combobox value after successfully record operations, or just call it
private void RowDeleter(ComboBox myComboBox)
{
try
{
SqlConnection conn = new SqlConnection(dataconnection);
SqlCommand cmd = new SqlCommand("myconn", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "yourtableset");
//look at what it is
String selectedId = (ComboBoxItem)(myComboBox.SelectedItem).Value.ToString();
DeleteRecord(selectedId);
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
// delete Helper
private void DeleteRecord(string row)
{
return if (StringIsNullOrEmpty(row))
string sql = "DELETE FROM Table1 WHERE RowID = #row";
SqlCommand deleteRecord = new SqlCommand();
deleteRecord.Connection = someconnection;
deleteRecord.CommandType = CommandType.Text;
deleteRecord.CommandText = sql;
SqlParameter RowParameter = new SqlParameter();
RowParameter.ParameterName = "#RowID";
RowParameter.SqlDbType = SqlDbType.string; //or int
RowParameter.IsNullable = false;
RowParameter.Value = row;
deleteRecord.Parameters.Add(RowParameter);
deleteRecord.Connection.Open();
deleteRecord.ExecuteNonQuery();
deleteRecord.Connection.Close();
booksDataset1.GetChanges();
// sqlDataAdapter1.Fill(someDataset.WHatverEmployees);
}
I have a comboBox and a checkListBox in my windows form application that connected to my SQL database. I got the binding data part working, but I am not sure how to show the datas in checkListBox when the comboBox item is selected. Let say I have 10 items in my comboBox that bind with my SQL database and they are under the column name ("application name ") such as excel, word, android, eclipse etc.... I call this method when the form begin to load. Sorry for the long code.
Here is my code for that applicationComboBox
private void loadComboBox()
{
myConn = new SqlConnection("Server = localhost; Initial Catalog= dbName; Trusted_Connection = True");
try
{
myConn.Open();
//my table name is Application_Detail
string query = "select * from Application_Detail";
myCommand = new SqlCommand(query, myConn);
//reading the value from the query
SqlDataReader dr = myCommand.ExecuteReader();
//Reading all the value one by one
while (dr.Read())
{
//column is 1 in Application_Detail Data
//GetString(1) display the 2nd column of the table
string name = dr.GetString(1);
//display the application name in column 2 -
applicationComboBox.Items.Add(name);
}
myConn.Close();
}catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
The outcome of this part of code is:
//label Name //Application Name
Application Name:
Excel
Word
NotePad
PowerPoint
SubLime
Eclipse
After I call this method, I want to display the teacher name that is according to what the user selected in this applicationComboBox. So if teacher 1,2,3 is using Excel and the user selected excel from the comboBox, the checkListBox will display teacher 1,2,3 and vice versa. To do this, I call the method at the comboBox1_SelectedIndexChanged method because I want to display the detail when I select an item from the comboBox. Below is my code
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
//I check if the comboBox index is at 0, it disable the button.
if (applicationComboBox.SelectedIndex == 0)
{
exportButton.Enabled = false;
this.teacherCheckListBox.DataSource = null;
teacherCheckListBox.Items.Clear();
}
//it it is not at 0,
else
{
exportButton.Enabled = true;
//call this method
fill_checkListBox();
}
//teacherCheckListBox
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void fill_checkListBox()
{
myConn = new SqlConnection("Server = localhost; Initial Catalog= dbName; Trusted_Connection = True");
try
{
myConn.Open();
//for reading purpose, I break down by long statement
//In this statement, I left join 3 table (Teacher_Detail, AppUser_Detail, and Application_Detail table). My AppUser_Detail contains all 3 id (teacherId, applicationId, and AppUserId). I then set filter the table using `where` keyWord to make the applicationId = the comboBox text
string query = "SELECT
td.chineseName,
ad.applicationId,
aud.applicationId,
ad.applicationName
FROM[AppUser_Detail] as aud
LEFT JOIN[Teacher_Detail] as td
ON aud.teacherId = td.teacherId
LEFT JOIN[Application_Detail] as ad
ON aud.applicationId = ad.applicationId
where aud.applicationId = '" + applicationComboBox.Text + "' AND NOT(td.teacherId IS NULL)
";
myCommand = new SqlCommand(query, myConn);
//reading the value from the query
SqlDataReader dr = myCommand.ExecuteReader();
//Reading all the value one by one
while (dr.Read())
{
//column is 0 where the teacherName belong in my Teacher_Detail table
string name = dr.GetString(0);
//I tried to set the text of the checkListBox as the teacherName, but I can't somehow
teacherCheckListBox.Text = name;
}
myConn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
When I run the program like this, it said Conversion failed when converting the varchar value "Excel" to data type int. Is there a way to fix it? it shouldn't be a problem because in my Application_Detail table, my applicationName's and my teacherName's data type is set as nvarchar(50) and applicationId and teacherId = int;
The problem is with this line, I would think:
where aud.applicationId = '" + applicationComboBox.Text +
Based on your code, I would think that applicationId is an int and applicationComboBox.Text is just that, text.
Try this:
where ad.applicationName = '" + applicationComboBox.Text.Trim() +
Try this:
if (string.IsNullOrWhiteSpace(teacherCheckListBox.FindString(name))
{
teacherCheckListBox.Items.Add(name);
}
I'm attempting to fill a DataTable with results pulled from a MySQL database, however the DataTable, although it is initialised, doesn't populate. I wanted to use this DataTable to fill a ListView. Here's what I've got for the setting of the DataTable:
public DataTable SelectCharacters(string loginName)
{
this.Initialise();
string connection = "0.0.0.0";
string query = "SELECT * FROM characters WHERE _SteamName = '" + loginName + "'";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataAdapter returnVal = new MySqlDataAdapter(query,connection);
DataTable dt = new DataTable("CharacterInfo");
returnVal.Fill(dt);
this.CloseConnection();
return dt;
}
else
{
this.CloseConnection();
DataTable dt = new DataTable("CharacterInfo");
return dt;
}
}
And for the filling of the ListView, I've got:
private void button1_Click(object sender, EventArgs e)
{
string searchCriteria = textBox1.Text;
dt = characterDatabase.SelectCharacters(searchCriteria);
MessageBox.Show(dt.ToString());
listView1.View = View.Details;
ListViewItem iItem;
foreach (DataRow row in dt.Rows)
{
iItem = new ListViewItem();
for (int i = 0; i < row.ItemArray.Length; i++)
{
if (i == 0)
iItem.Text = row.ItemArray[i].ToString();
else
iItem.SubItems.Add(row.ItemArray[i].ToString());
}
listView1.Items.Add(iItem);
}
}
Is there something I'm missing? The MessageBox was included so I could see if it has populated, to no luck.
Thanks for any help you can give.
Check your connection string and instead of using
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataAdapter returnVal = new MySqlDataAdapter(query,connection);
DataTable dt = new DataTable("CharacterInfo");
returnVal.Fill(dt);
this.CloseConnection();
return dt;
you can use this one
MySqlCommand cmd = new MySqlCommand(query, connection);
DataTable dt = new DataTable();
dt.load(cmd.ExecuteReader());
return dt;
Well, I ... can't figure out what you have done here so I'll paste you my code with which I'm filling datagridview:
1) Connection should look something like this(if localhost is your server, else, IP adress of server machine):
string connection = #"server=localhost;uid=root;password=*******;database=*******;port=3306;charset=utf8";
2) Query is ok(it will return you something), but you shouldn't build SQL statements like that.. use parameters instead. See SQL injection.
3) Code:
void SelectAllFrom(string query, DataGridView dgv)
{
_dataTable.Clear();
try
{
_conn = new MySqlConnection(connection);
_conn.Open();
_cmd = new MySqlCommand
{
Connection = _conn,
CommandText = query
};
_cmd.ExecuteNonQuery();
_da = new MySqlDataAdapter(_cmd);
_da.Fill(_dataTable);
_cb = new MySqlCommandBuilder(_da);
dgv.DataSource = _dataTable;
dgv.DataMember = _dataTable.TableName;
dgv.AutoResizeColumns();
_conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (_conn != null) _conn.Close();
}
}
So, every time I want to display some content of table in mysql database I call this method, pass query string and datagridview name to that method. and, that is it.
For your sake, compare this example with your and see what can you use from both of it. Maybe, listview is not the best thing for you, just saying ...
hope that this will help you a little bit.
Debug your application and see if your sql statement/ connection string is correct and returns some value, also verify if your application is not throwing any exception.
Your connection string is invalid.
Set it as follows:
connection = "Server=myServer;Database=myDataBase;Uid=myUser;Pwd=myPassword;";
Refer: mysql connection strings
Here the following why the codes would not work.
Connection
The connection of your mySQL is invalid
Query
I guess do you want to search in the table, try this query
string query = "SELECT * FROM characters WHERE _SteamName LIKE '" + loginName + "%'";
notice the LIKE and % this could help to list all the data. for more details String Comparison Functions