Right now I have this:
da = new SqlDataAdapter("SELECT * FROM LOGIN WHERE RECHTEN=2", conn);
dtt = new DataTable();
da.Fill(dtt);
for (int i = 0; i < dtt.Rows.Count; i++)
{
txtKlantid.Items.Add(dtt.Rows[i]["klantId"]);
}
Now it only shows the klantId, but I also want to show the name. And when I've that, so the klantId and the name how can I only select the klantId when I say:
selectedUserId = combobox.Text;
EDIT:
//THIS IS WHERE I INITIALISE THE COMBOBOX
da = new SqlDataAdapter("SELECT (kg.voornaam+' '+kg.achternaam + ' - ' + CONVERT(varchar,l.klantId)) AS dispValue FROM LOGIN l inner join klantGegevens kg on l.klantId=kg.klantid WHERE RECHTEN=2", conn);
dtt = new DataTable();
da.Fill(dtt);
txtKlantid.DisplayMember = "dispValue";
txtKlantid.ValueMember = "klantId";
txtKlantid.DataSource = dtt;
//THIS IS THE BUTTON FOR DELETING A USER
private void btnDeleteUser_Click(object sender, EventArgs e)
{
if (userInformation.addPersonsPermission)
{
int selectedUserId = Convert.ToInt32(((DataRowView)txtKlantid.SelectedValue)["klantId"]);
if (users.deleteKlantAdmin(selectedUserId))
{
MetroMessageBox.Show(this, "Gebruiker "+selectedUserId+" is verwijderd", "Verwijderd");
}
else
{
MetroMessageBox.Show(this, "Er ging iets fout, contacteer de beheerder", "Fout");
}
}
else
{
loginAddUser addUserLogin = new loginAddUser();
addUserLogin.ShowDialog();
}
}
You can use DisplayMember and ValueMember property of ComboBox
da = new SqlDataAdapter("SELECT * FROM LOGIN WHERE RECHTEN=2", conn);
dtt = new DataTable();
da.Fill(dtt);
txtKlantid.DisplayMember = "Name"; //Name of field to display
txtKlantid.ValueMember = "klantId";
txtKlantid.DataSource = dtt;
And you can get Name And Id back by following
var name = txtKlantid.Text;
var id = txtKlantid.SelectedValue;
As per your requirement you can combine Id and Name
for (int i = 0; i < dtt.Rows.Count; i++)
{
txtKlantid.Items.Add(dtt.Rows[i]["klantId"].ToString()+"-"+dtt.Rows[i]["Name"].ToString());
}
DisplayMember and ValueMember properties will be your friends in this case.
Please avoid selecting all the fields from the table just to fill your combobox. You can just do something like,
da = new SqlDataAdapter("SELECT (name + ' - ' + CONVERT(varchar,klantId)) AS dispValue, klantId FROM LOGIN WHERE RECHTEN=2", conn);
dtt = new DataTable();
da.Fill(dtt);
txtKlantid.DisplayMember = "dispValue";
txtKlantid.ValueMember = "klantId";
txtKlantid.DataSource = dtt;
In this example, txtKlantid.SelectedValue will give you the klantId values and txtKlantid.Text will give you the name - klantId values.
Hope this helps...
Related
I have a form with two combo boxes which both have a list from a database. In this case one is a list of countries and based on the value selected there, the second list is updated to show only the cities that belong to the selected country. After that, the values are combined and stored in my program like "city, country".
When I open my form I retrieve that information and separate the values back to just country and city. All working. The trouble I have now is that the comboboxes should display the retrieved values if the correspond to a value found in the list/database. I tried as shown below, but that is not working. I guess it has something to do with adding a new row to the database to show "--Select Country--" and "--Select City--".
I hope you can point me in the right direction. Thank you all in advance for your replies.
comboBoxCountry.SelectedValue = comboBoxCountry.FindString(country);
comboBoxCity.SelectedValue = comboBoxCity.FindString(city);
public partial class FormPropertyEditor : Form
{
//Connect to local database.mdf
SqlConnection con = new SqlConnection("Data Source = (LocalDB)\\MSSQLLocalDB;AttachDbFilename=" +
#"C:\Users\gleonvanlier\AppData\Roaming\Autodesk\ApplicationPlugins\MHS Property Editor\Database.mdf;" +
"Integrated Security=True;Connect Timeout=30;User Instance=False;");
DataRow dr;
public FormPropertyEditor()
{
InitializeComponent();
ReadProperties();
refreshdata();
}
public void refreshdata()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from TblCountries Order by CountryName", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Close();
dr = dt.NewRow();
dr.ItemArray = new object[] { 0, "--Select Country--" };
dt.Rows.InsertAt(dr, 0);
comboBoxCountry.ValueMember = "CountryID";
comboBoxCountry.DisplayMember = "CountryName";
comboBoxCountry.DataSource = dt;
comboBoxCountry.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBoxCountry.AutoCompleteSource = AutoCompleteSource.ListItems;
}
private void comboBoxCountry_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBoxCountry.SelectedValue.ToString() != null)
{
int CountryID = Convert.ToInt32(comboBoxCountry.SelectedValue.ToString());
refreshstate(CountryID);
}
}
public void refreshstate(int CountryID)
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from TblCities where CountryID= #CountryID Order by CityName", con);
cmd.Parameters.AddWithValue("CountryID", CountryID);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Close();
dr = dt.NewRow();
dr.ItemArray = new object[] { 0, 0, "--Select City--" };
dt.Rows.InsertAt(dr, 0);
comboBoxCity.ValueMember = "CityID";
comboBoxCity.DisplayMember = "CityName";
comboBoxCity.DataSource = dt;
comboBoxCity.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBoxCity.AutoCompleteSource = AutoCompleteSource.ListItems;
}
private void ReadProperties()
{
string progId = "Inventor.Application";
Type inventorApplicationType = Type.GetTypeFromProgID(progId);
Inventor.Application invApp = (Inventor.Application)Marshal.GetActiveObject(progId);
//Get the active document in Inventor
Document oDoc = (Document)invApp.ActiveDocument;
ReadProperties readProperties = new ReadProperties();
//Read Customer
string txtCustomer = readProperties.ReadCustomProperty("Customer", oDoc).ToString();
this.textBoxCustomer.Text = txtCustomer;
//Read Location
string txtLocation = readProperties.ReadCustomProperty("Location", oDoc).ToString();
try
{
string[] location = txtLocation.Split(',', ' ');
string city = location[0];
string country = location[1];
comboBoxCountry.SelectedValue = comboBoxCountry.FindString(country);
comboBoxCity.SelectedValue = comboBoxCity.FindString(city);
}
catch (Exception e)
{
string city = string.Empty;
string country = string.Empty;
}
}
This solved it:
comboBoxCountry.SelectedIndex = comboBoxCountry.FindStringExact(country);
comboBoxCity.SelectedIndex = comboBoxCity.FindStringExact(city);
I have 3 listboxes.The listbox fetches two values by code-datatextfield and datavaluefield. 1st listbox transfers the datatextfield items from 1st listbox to 2nd listbox.i want to transfer the datavaluefield of selected 1st listbox items to 3rd listbox.
if (ListBox3.SelectedIndex >= 0
{
for (int i = 0; i < ListBox3.Items.Count; i++)
{
if (ListBox3.Items[i].Selected)
{
if (!arraylist1.Contains(ListBox3.Items[i]))
{
arraylist1.Add(ListBox3.Items[i]);
Session["value"] = ListBox3.Items[i];
}
}
}
for (int i = 0; i < arraylist1.Count; i++)
{
if (!ListBox2.Items.Contains(((ListItem)arraylist1[i])))
{
ListBox2.Items.Add(((ListItem)arraylist1[i]));
}
ListBox3.Items.Remove(((ListItem)arraylist1[i]));
}
ListBox2.SelectedIndex = -1;
}
else
{
}
SqlConnection con = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("select * from IT_1_BOILER_DESK_1_PARAMETERS where paramtext='" + Session["value"] + "'", con);
SqlDataAdapter dataAadpter = new SqlDataAdapter(command);
DataSet ds = new DataSet();
dataAadpter.Fill(ds);
if (ds != null)
{
ListBox1.DataSource = ds.Tables[0];
ListBox1.DataTextField = "param";
//ListBox3.DataValueField = "param";
ListBox1.DataBind();
}
for listbox 3
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("select * from IT_1_BOILER_DESK_1_PARAMETERS where pname='" + this.DropDownList1.SelectedValue + "'" ,con);
SqlDataAdapter dataAadpter = new SqlDataAdapter(command);
DataSet ds = new DataSet();
dataAadpter.Fill(ds);
if (ds != null)
{
ListBox3.DataSource = ds.Tables[0];
ListBox3.DataTextField = "paramtext";
ListBox3.DataValueField = "param";
ListBox3.DataBind();
}
}
But i want to display the datavaluefield of the items that are selected from listbox3 to listbox1
Since you want to show DataTextField value and DataValueField value from one listbox into 2 different listbox. I suggest you to use a different approach. This will also reduce usage of 2nd database call.
Try following:-
if (ListBox3.SelectedIndex >= 0)
{
for (int i = 0; i < ListBox3.Items.Count; i++)
{
if (ListBox3.Items[i].Selected)
{
if (!arraylist1.Contains(ListBox3.Items[i]))
{
arraylist1.Add(ListBox3.Items[i]);
//Session["value"] = ListBox3.Items[i]; no need of this
}
}
}
for (int i = 0; i < arraylist1.Count; i++)
{
if (ListBox2.Items.FindByText(((ListItem)arraylist1[i]).Text)==null)
{
//since you already have text and value field values in arrayList. Use them
ListBox2.Items.Add(new ListItem(((ListItem)arraylist1[i]).Text));
}
if (ListBox1.Items.FindByText(((ListItem)arraylist1[i]).Text)==null)
{
ListBox1.Items.Add(new ListItem((ListItem)arraylist1[i]).Value));
}
ListBox3.Items.Remove(((ListItem)arraylist1[i]));
}
ListBox2.SelectedIndex = -1;
}
else
{
}
/* This database call can be removed
SqlConnection con = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("select * from IT_1_BOILER_DESK_1_PARAMETERS where paramtext='" + Session["value"] + "'", con);
SqlDataAdapter dataAadpter = new SqlDataAdapter(command);
DataSet ds = new DataSet();
dataAadpter.Fill(ds);
if (ds != null)
{
ListBox1.DataSource = ds.Tables[0];
ListBox1.DataTextField = "param";
//ListBox3.DataValueField = "param";
ListBox1.DataBind();
}*/
please help me I stuck in datagridview in c# winforms where my sql table looks like below
empcode-varchar(50)
fullname-varchar(50)
month-date
branch-varchar(50)
designation-varchar(50)
id-varchar(50)
accountno-nvarchar(50)
paymenttype-nvarchar(50)
basicsal-int
ca-int
hra-int
sa-int
totalsalary-int
allowanceid-int(IDENTITY COLUMN)
remark-nvarchar(50)
For this table i took two buttons one is viewdata and another is delete
my view data coding part working fine and is shown below:-
SqlDataAdapter da = new SqlDataAdapter("select * from allowance", cn);
dt = new System.Data.DataTable();
da.Fill(dt);
dg2.Rows.Clear();
foreach (DataRow item in dt.Rows)
{
int n = dg2.Rows.Add();
dg2.Rows[n].Cells[0].Value = false;
dg2.Rows[n].Cells[1].Value = item["empcode"].ToString();
dg2.Rows[n].Cells[2].Value = item["fullname"].ToString();
dg2.Rows[n].Cells[3].Value = item["month"].ToString();
dg2.Rows[n].Cells[4].Value = item["branch"].ToString();
dg2.Rows[n].Cells[5].Value = item["designation"].ToString();
dg2.Rows[n].Cells[6].Value = item["id"].ToString();
dg2.Rows[n].Cells[7].Value = item["accountno"].ToString();
dg2.Rows[n].Cells[8].Value = item["paymenttype"].ToString();
dg2.Rows[n].Cells[9].Value = item["basicsal"].ToString();
dg2.Rows[n].Cells[10].Value = item["ca"].ToString();
dg2.Rows[n].Cells[11].Value = item["hra"].ToString();
dg2.Rows[n].Cells[12].Value = item["sa"].ToString();
dg2.Rows[n].Cells[13].Value = item["totalsalary"].ToString();
dg2.Rows[n].Cells[14].Value = item["allowanceid"].ToString();
dg2.Rows[n].Cells[15].Value = item["remark"].ToString();
}
and another button "delete" code is looks like this way:-
foreach (DataGridViewRow itemRow in dg2.Rows)
{
if (bool.Parse(itemRow.Cells[14].Value.ToString()))
{
da = new SqlDataAdapter("DELETE FROM allowance WHERE allowanceid = '" + itemRow.Cells[14].Value.ToString() + "'", cn);
DataTable bb = new DataTable();
da.Fill(bb);
}
}
MessageBox.Show("SuccessFully DELETED.....!");
foreach (DataGridViewRow itemRow in dg2.Rows)
{
if (!itemRow.IsNewRow)
{
if ((bool)itemRow.Cells[0].EditedFormattedValue)
{
da = new SqlDataAdapter("DELETE FROM allowance WHERE allowanceid = " + Convert.ToInt32(itemRow.Cells[14].Value) + "", cn);
DataTable bb = new DataTable();
da.Fill(bb);
try this
foreach (DataGridViewRow itemRow in dg2.Rows)
{
if (bool.Parse(Convert.Tostring(itemRow.Cells[14].Value)))
{
da = new SqlDataAdapter("DELETE FROM allowance WHERE allowanceid = '" + Convert.Tostring(itemRow.Cells[14].Value) + "'", cn);
DataTable bb = new DataTable();
da.Fill(bb);
}
}
MessageBox.Show("SuccessFully DELETED.....!");
wire this code in DaataError Event
private void DGData_DataError(object sender, DataGridViewDataErrorEventArgs anError)
{
if ((anError.Exception) is ConstraintException)
{
DataGridView grd1 = (DataGridView)sender;
grd1.Rows[anError.RowIndex].ErrorText = "an error";
grd1.Rows[anError.RowIndex].Cells[anError.ColumnIndex].ErrorText = "an error";
anError.ThrowException = false;
}
}
}
I tried bind the DataGridView from Table "NatureCharge"
private void BindGrid()
{
DataGridViewNatureCharge.DataSource = null;
using (SqlConnection con = new SqlConnection(connstring))
{
using (SqlCommand cmd = new SqlCommand("select * from NatureCharge", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
DataGridViewNatureCharge.DataSource = dt;
}
}
}
}
}
But I need to show Nom Famille not the Id, so what is the modification on select query???
"select * from NatureCharge where Idfam =(select NomFam from Famille)"
Update
the problem with NomFam created in another cell in DatagridView.
I need to add it in 3rd cell.
select n.IdNat,n.NomNat,f.NomFam from NatureCharge n join Famille f on n.IdFam=f.IdFam
The DataGridView
//Set Columns Count
DataGridViewNatureCharge.ColumnCount = 3;
//Hide the last blank line
DataGridViewNatureCharge.AllowUserToAddRows = false;
//Add Columns
DataGridViewNatureCharge.Columns[0].Name = "IdNat";
DataGridViewNatureCharge.Columns[0].HeaderText = "N° Nature de Charge";
DataGridViewNatureCharge.Columns[0].DataPropertyName = "IdNat";
DataGridViewNatureCharge.Columns[0].Width = 100;
DataGridViewNatureCharge.Columns[1].HeaderText = "Nom de Nature de Charge";
DataGridViewNatureCharge.Columns[1].Name = "NomNat";
DataGridViewNatureCharge.Columns[1].DataPropertyName = "NomNat";
DataGridViewNatureCharge.Columns[1].Width = 150;
DataGridViewNatureCharge.Columns[2].Name = "IdFam";
DataGridViewNatureCharge.Columns[2].HeaderText = "Nom de Famille";
DataGridViewNatureCharge.Columns[2].DataPropertyName = "IdFam";
DataGridViewNatureCharge.Columns[2].Width = 100;
DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
checkBoxColumn.HeaderText = "";
checkBoxColumn.Width = 30;
checkBoxColumn.Name = "checkBoxColumn";
DataGridViewNatureCharge.Columns.Insert(0, checkBoxColumn);
Use SQL joins for this.
SELECT A.NomFam, B.IdNat, B.NomNat FROM Famille A join NatureChange B on A.IdFam = B.IdFam
I have two datagridviews in one from. I need to get data from database to datagridview1 (using Select *from database...) then I want to add data from datagriwview to datagridview2 using Selected Rows.
First I wanted to solve this problem to get Selected Row's ID, when I select row in datagridview it shows in datagridview2, but when I select another row, it is updating in datagridview, it does not add as new row. I tried several ways but did not solve this problem, Is there anyone help me to solve this problem? Thanks
private void dataGridView1_CellDoubleClick_1(object sender, DataGridViewCellEventArgs e)
{
int id = Convert.ToInt32
(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells["id"].Value);//3
try
{
MySqlConnection conn = new MySqlConnection(connection);
MySqlCommand command = start.CreateCommand();
command.CommandText = "SELECT id, muayine_adi, sabit_qiymet FROM tibbi_xidmetler WHERE id = '" + id.ToString() + "'";
conn.Open();
MySqlDataAdapter oxu = new MySqlDataAdapter(command);
DataTable dt = new DataTable();
oxu.Fill(dt);
dataGridView2.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Is quite simple the explanation: everytime that you make a double click to a datagridview1's cell you replace the old datatable with a new one. If you want append the result you can do something like this:
MySqlConnection conn = new MySqlConnection(connection);
MySqlCommand command = start.CreateCommand();
command.CommandText = "SELECT id, muayine_adi, sabit_qiymet FROM tibbi_xidmetler WHERE id = '" + id.ToString() + "'";
conn.Open();
MySqlDataAdapter oxu = new MySqlDataAdapter(command);
DataTable dt = new DataTable();
oxu.Fill(dt);
if(dataGridView2.DataSource != null) {
DataTable pr = dataGridView2.DataSource as DataTable;
pr.Merge(dt);
dataGridView2.DataSource = pr;
}
else
dataGridView2.DataSource = dt;
Since you have all information in datagridview1 you should just copy the contents of the selected row into a new row for datagridrow2.
The DataGridView is based on a DataSet which contains DataTables.
The DataTable contains rows.
You cannot move a row from one table to annother.
Instead you have to create a new row and insert into the DataTable of DataGridView2
private void dataGridView1_CellDoubleClick_1(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.CurrentRow.Cells["Id"].Value != null)
{
int Id = Convert.ToInt32(dataGridView1.CurrentRow.Cells["Id"].Value);
MySqlConnection start = new MySqlConnection(baglanti);
MySqlCommand command = start.CreateCommand();
command.CommandText = "SELECT id, muayine_adi, sabit_qiymet FROM tibbi_xidmetler WHERE id = '" + Id + "'";
start.Open();
MySqlDataAdapter oxu = new MySqlDataAdapter(command);
DataTable dt = new DataTable();
oxu.Fill(dt);
if (dt != null && dt.Rows.Count > 0)
{
int idx = dataGridView2.Rows.Count - 1;
dataGridView2.Rows.Add(dt.Rows.Count);
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
int rVal = (idx + i) + 1;
dataGridView2.Rows[rVal].Cells["id"].Value = dt.Rows[i]["id"].ToString();
dataGridView2.Rows[rVal].Cells["muayine_adi"].Value = dt.Rows[i]["muayine_adi"].ToString();
dataGridView2.Rows[rVal].Cells["sabit_qiymet"].Value = dt.Rows[i]["sabit_qiymet"].ToString();
}
}
start.Close();
}
}