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
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 want to display a Comboxbox Item, depending on a data table.
for example:
1 = open
2 = close
....
The combobox content is created with the datatable:
string sqlStr = "select id, description from sdg.pa_status";
MySqlDataAdapter adapt = new MySqlDataAdapter();
MySqlCommand cmd = new MySqlCommand();
DataSet ds = new DataSet();
cmd = new MySqlCommand(sqlStr, conn);
adapt.SelectCommand = cmd;
adapt.Fill(ds);
**_status** = ds.Tables[0];
combox is created:
column.Name = "status";
column.DropDownWidth = 160;
column.Width = 160;
column.FlatStyle = 0;
column.HeaderText = "Status";
column.DataSource = **_status**;
column.DataPropertyName = dGVQuote.Columns["**stat**"].ToString();
column.ValueMember = _status.Columns[1].ToString();
column.DisplayMember = _status.Columns[1].ToString();
datagrid is generated:
private void CustomizeDataGridViewOrder()
{
dGVQuote.DataSource = GetQuote("");
dGVQuote.Columns["ID"].Width = 135;
dGVQuote.Columns["ID"].HeaderText = "Angebotsnummer";
dGVQuote.Columns["idorder"].Visible = false;
dGVQuote.Columns["Description"].Width = 225;
dGVQuote.Columns["Description"].HeaderText = "Beschreibung";
dGVQuote.Columns["comment"].Width = 225;
dGVQuote.Columns["comment"].HeaderText = "interner Kommentar";
dGVQuote.Columns["idcust"].Visible = false;
dGVQuote.Columns["idobj"].Visible = false;
dGVQuote.Columns["cnt"].Width = 60;
dGVQuote.Columns["cnt"].HeaderText = "Anzahl MA";
dGVQuote.Columns["**stat**"].Visible = true;
dGVQuote.Columns.Add(CreateComboBoxColumn());
dGVQuote.Columns["valid"].Width = 135;
dGVQuote.Columns["valid"].HeaderText = "gültig bis";
dGVQuote.DataSource = GetQuote(""); //datatable is handed over
I am desperate. Can someone help me?
net sql server , I want a loop to retrieve data from sql database to different label controls using C# asp.net sql server storedprocedure.
string constrng = ConfigurationManager.ConnectionStrings["baby"].ConnectionString;
SqlConnection conn = new SqlConnection(constrng);
SqlCommand sqlComm;
sqlComm = new SqlCommand("stor_proc", conn);
sqlComm.CommandType = System.Data.CommandType.StoredProcedure;
conn.Open();
SqlDataReader dr = sqlComm.ExecuteReader();
DataSet ds = new DataSet();
ds.Tables.Add("Home");
ds.Tables[0].Load(dr);
m.Text = ds.Tables[0].Rows[0][1].ToString();
i.Text = ds.Tables[0].Rows[0][2].ToString();
d.Text = ds.Tables[0].Rows[0][3].ToString();
g.Text = ds.Tables[0].Rows[0][4].ToString();
m1.Text = ds.Tables[0].Rows[1][1].ToString();
i1.Text = ds.Tables[0].Rows[1][2].ToString();
d1.Text = ds.Tables[0].Rows[1][3].ToString();
g1.Text = ds.Tables[0].Rows[1][4].ToString();
m2.Text = ds.Tables[0].Rows[2][1].ToString();
i2.Text = ds.Tables[0].Rows[2][2].ToString();
d2.Text = ds.Tables[0].Rows[2][3].ToString();
g2.Text = ds.Tables[0].Rows[2][4].ToString();
conn.Close();
for (int i = 0; i < 3; i++ ) {
m.Text = ds.Tables[0].Rows[i][1].ToString();
i.Text = ds.Tables[0].Rows[i][2].ToString();
d.Text = ds.Tables[0].Rows[i][3].ToString();
g.Text = ds.Tables[0].Rows[i][4].ToString();
}
You can use a foreach loop like this:
foreach (DataRow row in ds.Tables[0].Rows)
{
// Now here, you are iterating through a individual row.
// ItemArray gives an index position of a cell within a row.
m.Text = row.ItemArray[0].ToString();
i.Text = row.ItemArray[1].ToString();
d.Text = row.ItemArray[2].ToString();
g.Text = row.ItemArray[3].ToString();
}
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...
I am trying to display ajax bar chart in my web page. But it is only displaying one value .
My db contains 3 columns(name, credit, debit) I want to display the credit debit values in chart. But the chart is only displaying one value. How can I modify the given below coding. Thank you.
Code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string query = "select Name from aTable";
DataTable dt = GetData(query);
ddlCountries.DataSource = dt;
ddlCountries.DataTextField = "Name";
ddlCountries.DataValueField = "Name";
ddlCountries.DataBind();
ddlCountries.Items.Insert(0, new ListItem("Select", ""));
}
}
private DataTable GetData(string query, SqlParameter[] prms = null)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["demoConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
if (prms != null)
cmd.Parameters.AddRange(prms);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
protected void ddlCountries_SelectedIndexChanged(object sender, EventArgs e)
{
string query = "select Name, Debit, Credit From aTable where Name=#Name";
SqlParameter[] prms = new SqlParameter[1];
prms[0] = new SqlParameter("#name", SqlDbType.NVarChar);
prms[0].Value = ddlCountries.SelectedItem.Value.ToString();
DataTable dt = GetData(query, prms);
string[] x = new string[dt.Rows.Count];
decimal[] y = new decimal[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
x[i] = dt.Rows[i][0].ToString();
y[i] = Convert.ToInt32(dt.Rows[i][1]);
}
BarChart1.Series.Add(new AjaxControlToolkit.BarChartSeries { Data = y });
BarChart1.CategoriesAxis = string.Join(",", x);
BarChart1.ChartTitle = string.Format("{0} -RunTimeReportChart", ddlCountries.SelectedItem.Value);
if (x.Length > 3)
{
BarChart1.ChartWidth = (x.Length * 100).ToString();
}
BarChart1.Visible = ddlCountries.SelectedItem.Value != "";
}
Data Base:
Actual Output:
The given below chart is only displaying the name and debit value. I want to display the credit value also. Please help me.
Something Like :
decimal[] z = new decimal[dt.Rows.Count];
z[i] = Convert.ToInt32(dt.Rows[i][2]);
BarChart1.Series.Add(new AjaxControlToolkit.BarChartSeries { Data = z });