Putting Values in Controls when dynamically creating a form - c#

I have been working on an issue for a while and I finally figured it out. I was trying to set a control when the Form is being initialize. I am thinking that the control's value isn't being set is because the control has been drawn yet (CORRECT ME IF I AM WRONG).
My partial form code
//in form 1
....
private void button2_Click(object sender, EventArgs e)
{
Form2 form = new Form2();
form.Owner = this;
form.Show(this);
}
....}
public Form2()
{
InitializeComponent();
setData(); //Sets a datagridview's combobox column and databinds a datatable
setGrid(); //Sets each row in the datagridview combobox's value to a string
}
private void setData()
{
gvTest.AllowUserToAddRows = false;
string strConn = "server=10.253.3.185;database=petersun-test1;user id=ctore;password=cqi$$;connection timeout=30";
SqlConnection conn = new SqlConnection(strConn);
DataTable dit = new DataTable();
try
{
conn.Open();
string sql = "SELECT LTRIM(RTRIM(COLUMN_NAME)) as ColumnName from INFORMATION_SCHEMA.COLUMNS where Table_Name='coproc' order by ORDINAL_POSITION";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dit);
DataGridViewComboBoxColumn dcDatabasefields = new DataGridViewComboBoxColumn();
dcDatabasefields.DataPropertyName = "ColumnName";
dcDatabasefields.HeaderText = "Database Field Name";
dcDatabasefields.Name = "dbFields";
dcDatabasefields.DisplayMember = "ColumnName";
dcDatabasefields.ValueMember = "ColumnName";
dcDatabasefields.Width = 200;
BindingSource bsourceFields = new BindingSource();
bsourceFields.DataSource = dit;
dcDatabasefields.DataSource = bsourceFields;
dcDatabasefields.DataSource = dit; // bsourceFields;
gvTest.Columns.Add(dcDatabasefields);
}
finally
{
conn.Close();
}
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("options");
dt.Columns.Add(dc);
DataRow dr = dt.NewRow();
dr["options"] = "A";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["options"] = "C";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["options"] = "D";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["options"] = "E";
dt.Rows.Add(dr);
gvTest.DataSource = dt;
}
private void setGrid()
{
foreach(DataGridView Row in gvGrid.Rows)
{
Row.Cells[0].Value = "string";
}
}
So what I think is happening is:
1. The component is getting initialized
2. Creates the datagridview with columns
3. Sets the column values
4. Draws the form
Is my thinking correct? My question is what form event should I set the control's value? I did some research and I am thinking on the PAINT event, but I am not sure either. Could someone explain the Form's life cycle in some detail or point me to somewhere.
Thanks

I just added the coded into the Form_load and it added the values to the grid

Related

Set value of combo box to collected value from source

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);

Textbox autocomplete not working

private void AutoComplete()
{
textBox4.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
textBox4.AutoCompleteSource = AutoCompleteSource.CustomSource;
AutoCompleteStringCollection col = new AutoCompleteStringCollection();
OleDbDataAdapter dAdapter2 = new OleDbDataAdapter("select ID from Car ", connParam);
OleDbCommandBuilder cBuilder2 = new OleDbCommandBuilder(dAdapter2);
DataTable dataTable2 = new DataTable();
DataSet ds2 = new DataSet();
dAdapter2.Fill(dataTable2);
foreach (DataRow row in dataTable2.Rows)
{
//TextBox1.Text = row["ImagePath"].ToString();
col.Add(row["ID"].ToString());
}
textBox4.AutoCompleteCustomSource = col;
}
I was calling this function in form load but not working
I also call the method on text_change but i faced the same problem that no values appeared

losing data entered in dataview C#

I am using Visual C# 2008 to make a application that takes the data from textboxes and displays it in datagridview in another form the conforming make it entered to the database.
I send the data using dataTable with a function entered the data without any symentic error but when I call the other for the datagridview comes empty and the database comes empty. When I duplicate a primary key it gives an error stating "cannot duplicate primary key".
This is the code for the function that transfers that datatable
public DataTable showout() {
DataTable dtab = new DataTable();
DataColumn dc1 = new DataColumn("رقم المتسلسل");
DataColumn dc2 = new DataColumn("رقم الحساب");
DataColumn dc3 = new DataColumn("أسم الحساب");
dtab.Columns.Add(dc1);
dtab.Columns.Add(dc2);
dtab.Columns.Add(dc3);
// Create an array for the values.
object[] newRow = new object[3];
// Set the values of the array.
string s = numb.Text;
newRow[0] =numb.Text;
newRow[1] = textBox5.Text;
newRow[2] =note.Text;
DataRow row;
dtab.BeginLoadData();
// Add the new row to the rows collection.
row = dtab.LoadDataRow(newRow, true);
return dtab;
}
this is the code that I call the function in the other From
private void Cashagree_Load(object sender, EventArgs e) {
dataGridView1.DataSource = ch.showout();
}
the second datagrid entering function its in the same class
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.Visible = true;
dataGridView1.DataSource = showout();
entering(true);
}
and this is the entering to the database
public void entering(bool bl)
{try{
if (bl)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
DateTime Date = DateTime.Today;
SqlCommand cmd = new SqlCommand("INSERT INTO Accont(Account_ID,Account_Name,Owners,Curency,Curncytype,Depet,Credet_devet,Date,Note) VALUES (#AccountID, #AccountName, #Owner, #Curncy,#Curncytype,#Depet,#Cridetdevet,#Date,#Note)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#AccountID",numb.Text);
cmd.Parameters.AddWithValue("#AccountName", comboBox1.SelectedText.ToString());
cmd.Parameters.AddWithValue("#Owner", owner.Text);
cmd.Parameters.AddWithValue("#Curncy", curency.Text);
cmd.Parameters.AddWithValue("#Curncytype", curncyval.Text);
cmd.Parameters.AddWithValue("#Depet", Depet.Text);
cmd.Parameters.AddWithValue("#Cridetdevet", textBox5.Text);
cmd.Parameters.AddWithValue("#Date", Date);
cmd.Parameters.AddWithValue("#Note", note.Text);
connection.Open();//Owner
cmd.ExecuteNonQuery();}}
}
catch(Exception ee)
{MessageBox.Show(ee.Message);}
the conforming from the another form
private void button1_Click_1(object sender, EventArgs e)
{
ch.entering(true);
Close();
}
Instead of using the dtab.LoadDataRow, you should be using the dtab.Rows.Add(datarow) method.
An example of how to do this:
public DataTable showout()
{
DataTable dtab = new DataTable();
// More efficient way of adding the columns with types:
dtab.Columns.Add("رقم المتسلسل", typeof(String));
dtab.Columns.Add("رقم الحساب", typeof(String));
dtab.Columns.Add("أسم الحساب", typeof(String));
/*
DataColumn dc1 = new DataColumn("رقم المتسلسل");
DataColumn dc2 = new DataColumn("رقم الحساب");
DataColumn dc3 = new DataColumn("أسم الحساب");
dtab.Columns.Add(dc1);
dtab.Columns.Add(dc2);
dtab.Columns.Add(dc3);
*/
// Create a new row using the .NewRow method
DataRow datRow = dtab.NewRow();
datRow["رقم المتسلسل"] = numb.Text;
datRow["رقم الحساب"] = textBox5.Text;
datRow["أسم الحساب"] = note.Text;
// Add the new row to the DataTable
dtab.Rows.Add(datRow);
return dtab;
}
Reference:
How to: Add Rows to a DataTable
Adding Data to a DataTable
In solve it by the sending the DataTable dt from the first Form cash to the second Form cashagree as a prameter by calling the method that return datagridview
in cash form I wrote this:
cashagree gc2 = cashagree(showout());
in cashagree form I wrote this
DataTable dt = new DstsTsble();
public cashagree(DataTable d2){
dt =d2;
}
and in the load of `cashagree_Load` I asign the datagridview datasoure
private void Cashagree_Load(object sender, EventArgs e)
{
if (dt.Rows[0].IsNull(dt.Columns[0]))
{
MessageBox.Show("There no primary key");
Close();
}
dataGridView1.DataSource = dt;
dataGridView1.Columns[7].Visible = false;// Iwantn't all the datatable so I diapple some Columns
dataGridView1.Columns[5].Visible = false;
dataGridView1.Columns[7].Visible = false;
dataGridView1.Columns[6].Visible = false;
dataGridView1.Columns[4].Visible = false;
}

how to bind datatable to datagridview in c#

I need to bind my DataTable to my DataGridView.
i do this:
DTable = new DataTable();
SBind = new BindingSource();
//ServersTable - DataGridView
for (int i = 0; i < ServersTable.ColumnCount; ++i)
{
DTable.Columns.Add(new DataColumn(ServersTable.Columns[i].Name));
}
for (int i = 0; i < Apps.Count; ++i)
{
DataRow r = DTable.NewRow();
r.BeginEdit();
foreach (DataColumn c in DTable.Columns)
{
r[c.ColumnName] = //writing values
}
r.EndEdit();
DTable.Rows.Add(r);
}
SBind.DataSource = DTable;
ServersTable.DataSource = SBind;
But all i got is DataTable ADDS NEW columns to my DataGridView.
I don't need this, i just need to write under existing columns.
Try this:
ServersTable.Columns.Clear();
ServersTable.DataSource = SBind;
If you don't want to clear all the existing columns, you have to set DataPropertyName for each existing column like this:
for (int i = 0; i < ServersTable.ColumnCount; ++i) {
DTable.Columns.Add(new DataColumn(ServersTable.Columns[i].Name));
ServersTable.Columns[i].DataPropertyName = ServersTable.Columns[i].Name;
}
Even better:
DataTable DTable = new DataTable();
BindingSource SBind = new BindingSource();
SBind.DataSource = DTable;
DataGridView ServersTable = new DataGridView();
ServersTable.AutoGenerateColumns = false;
ServersTable.DataSource = DTable;
ServersTable.DataSource = SBind;
ServersTable.Refresh();
You're telling the bindable source that it's bound to the DataTable, in-turn you need to tell your DataGridView not to auto-generate columns, so it will only pull the data in for the columns you've manually input into the control... lastly refresh the control to update the databind.
On the DataGridView, set the DataPropertyName of the columns to your column names of your DataTable.
// I built my datatable first, and populated it, columns, rows and all.
//Then, once the datatable is functional, do the following to bind it to the DGV. NOTE: the DGV's AutoGenerateColumns property must be 'true' for this example, or the "assigning" of column names from datatable to dgv will not work. I also "added" my datatable to a dataset previously, but I don't think that is necessary.
BindingSource SBind = new BindingSource();
SBind.DataSource = dtSourceData;
ADGView1.AutoGenerateColumns = true; //must be "true" here
ADGView1.Columns.Clear();
ADGView1.DataSource = SBind;
//set DGV's column names and headings from the Datatable properties
for (int i = 0; i < ADGView1.Columns.Count; i++)
{
ADGView1.Columns[i].DataPropertyName = dtSourceData.Columns[i].ColumnName;
ADGView1.Columns[i].HeaderText = dtSourceData.Columns[i].Caption;
}
ADGView1.Enabled = true;
ADGView1.Refresh();
foreach (DictionaryEntry entry in Hashtable)
{
datagridviewTZ.Rows.Add(entry.Key.ToString(), entry.Value.ToString());
}
private void Form1_Load(object sender, EventArgs e)
{
DataTable StudentDataTable = new DataTable("Student");
//perform this on the Load Event of the form
private void AddColumns()
{
StudentDataTable.Columns.Add("First_Int_Column", typeof(int));
StudentDataTable.Columns.Add("Second_String_Column", typeof(String));
this.dataGridViewDisplay.DataSource = StudentDataTable;
}
}
//Save_Button_Event to save the form field to the table which is then bind to the TableGridView
private void SaveForm()
{
StudentDataTable.Rows.Add(new object[] { textBoxFirst.Text, textBoxSecond.Text});
dataGridViewDisplay.DataSource = StudentDataTable;
}
for example we want to set a DataTable 'Users' to DataGridView by followig 2 steps :
step 1 - get all Users by :
public DataTable getAllUsers()
{
OracleConnection Connection = new OracleConnection(stringConnection);
Connection.ConnectionString = stringConnection;
Connection.Open();
DataSet dataSet = new DataSet();
OracleCommand cmd = new OracleCommand("semect * from Users");
cmd.CommandType = CommandType.Text;
cmd.Connection = Connection;
using (OracleDataAdapter dataAdapter = new OracleDataAdapter())
{
dataAdapter.SelectCommand = cmd;
dataAdapter.Fill(dataSet);
}
return dataSet.Tables[0];
}
step 2- set the return result to DataGridView :
public void setTableToDgv(DataGridView DGV, DataTable table)
{
DGV.DataSource = table;
}
using example:
setTableToDgv(dgv_client,getAllUsers());

loading combobox with datasource

i want to fill a combobox with data from the database when the page load
I had written the code as below
private void QuotationForm_Load(object sender, EventArgs e)
{
MessageBox.Show("hghjgvhg");
comboboxload();
}
public void comboboxload()
{
OleDbConnection oleDbConnection1 = new System.Data.OleDb.OleDbConnection(connString);
oleDbConnection1.Open();
OleDbCommand oleDbCommand1 = new System.Data.OleDb.OleDbCommand("Select jobpk,jobecode from jobcodemastertable",oleDbConnection1);
OleDbDataReader reader = oleDbCommand1.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("jobpk", typeof(int));
dt.Columns.Add("jobcode", typeof(string));
dt.Load(reader);
cmbjobcode.ValueMember = "jobpk";
cmbjobcode.DisplayMember = "jobcode";
cmbjobcode.DataSource = dt;
oleDbConnection1.Close();
}
it doesnot deturns an error or exception but doesnot load the combobox with data values
try this
comboBox1.DataSource = ds.Tables[0];
comboBox1.ValueMember = "id";
comboBox1.DisplayMember = "name";
You may need to bind datatable's view with combo box
cmbjobcode.DataSource = dt.DefaultView;
You're missing the DataBind method
dt.Load(reader);
cmbjobcode.ValueMember = "jobpk";
cmbjobcode.DisplayMember = "jobcode";
cmbjobcode.DataSource = dt;
//here
cmbjobcode.DataBind();
oleDbConnection1.Close();
You have to call DataBind method on your combo. Thats why its not populating.

Categories

Resources