I am developing an application in which I want to insert the data from the DataSet.
Following is my code to Insert the data:
WebForm1.aspx.cs:
public void Recieve_Data()
{
DataGridView.DataSource = obj.Get_Data();
DataGridView.DataBind();
}
public void Insert_Data()
{
TextBox StudentID = DataGridView.FooterRow.FindControl("TxtID") as TextBox;
TextBox StudentName = DataGridView.FooterRow.FindControl("TxtName") as TextBox;
TextBox StudentSex = DataGridView.FooterRow.FindControl("TxtSex") as TextBox;
TextBox StudentCity = DataGridView.FooterRow.FindControl("TxtCity") as TextBox;
int StuID = Convert.ToInt32(StudentID.Text);
string StuName = StudentName.Text;
string StuSex = StudentSex.Text;
string StuCity = StudentCity.Text;
obj.Insert_Data(StuID, StuName,StuSex, StuCity);
Recieve_Data();
}
My Insert_Data() is:
public void Insert_Data(int StuID, string StuName, string StuSex, string StuCity)
{
adap = new SqlDataAdapter("select * from Student", con);
DataSet ds = new DataSet();
adap.Fill(ds,"Student");
DataRow dr = ds.Tables[0].NewRow();
dr["ID"] = StuID;
dr["Name"] = StuName;
dr["Sex"] = StuSex;
dr["City"] = StuCity;
ds.Tables[0].Rows.Add(dr);
ds.Tables[0].AcceptChanges();
}
I am successfully receiving the new inserted record (seventh record) in the dataset at last:
But in the database, my table is not updated with the seventh row:
public void Insert_Data(int StuID, string StuName, string StuSex, string StuCity)
{
adap = new SqlDataAdapter("select * from Student", con);
SqlCommandBuilder cmdBuilder=new SqlCommandBuilder(adap);
DataSet ds = new DataSet();
adap.Fill(ds,"Student");
DataRow dr = ds.Tables[0].NewRow();
dr["ID"] = StuID;
dr["Name"] = StuName;
dr["Sex"] = StuSex;
dr["City"] = StuCity;
ds.Tables[0].Rows.Add(dr);
ds.Tables[0].AcceptChanges();
adap.Update(ds, "Student");
}
// Note: To reflect these change in DB you have to call "Update" method of SqlDataAdapter and the update method need Insert/update/Delete command to perform these operation on DB. I have used SqlcommandBuilder to generate the Insert/update/Delete, The Student table must have primary key to generate the insert /update /delete command using SqlcommandBuilder.
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'm trying to set values on items in combobox, but everytime I try so I get the result 'null'. Am I defining the value wrong or am I trying to get the value in a wrong way?
// Setting the value
sqlCmd.CommandText = "SELECT Id, Ime FROM Unajmljivaci WHERE Aktivan = 0";
conn.Open();
using (var reader = sqlCmd.ExecuteReader())
{
while (reader.Read())
{
cmbUnajmljivaci.Items.Add(new { Id = reader["Id"].ToString(), Ime = reader["Ime"].ToString() });
}
cmbUnajmljivaci.ValueMember = "Id"; // <---
cmbUnajmljivaci.DisplayMember = "Ime";
}
//Retrieving the value
sqlCmd.Parameters.AddWithValue("#SifraUnajmljivca", Convert.ToString(cmbUnajmljivaci.SelectedValue));
using (SqlConnection sqlConn = new SqlConnection("CONNECTION STRING"))
{
DataSet ds = new DataSet();
SqlCommand sqlCmd = sqlConn.CreateCommand();
sqlConn.Open();
SqlDataAdapter SQA_DataAdapter = new SqlDataAdapter(sqlCmd);
SQA_DataAdapter.SelectCommand = new SqlCommand("SELECT Id, Ime FROM Unajmljivaci WHERE Aktivan = 0", sqlConn);
SQA_DataAdapter.Fill(ds, "Table");
if (ds != null)
if (ds .Tables.Count > 0)
{
cmbUnajmljivaci.ValueMember = "Id";
cmbUnajmljivaci.DisplayMember = "Ime";
cmbUnajmljivaci.DataSource = ds.Tables[0];
}
sqlConn.Close();
}
You need to set the data source of the combobox.
Try getting the Value like this:
dynamic dyn = cmbUnajmljivaci.SelectedItem;
string s = dyn.Id;
Or even inline like this:
//Retrieving the value
sqlCmd.Parameters.AddWithValue("#SifraUnajmljivca", Convert.ToString(((dynamic)cmbUnajmljivaci.SelectedItem).Id);
Sample Code for Reference to your problem,
DataSet ds = new DataSet();
DataTable dt = ds.Tables.Add();
dt.Columns.Add("ID");
dt.Columns.Add("Name");
dt.Rows.Add("0", "Item1");
dt.Rows.Add("1", "Item2");
For inserting the item with specified index you need to use the below code
//Insert the item into the collection with specified index
foreach (DataRow row in dt.Rows)
{
int id = Convert.ToInt32(row["ID"]);
string name=row["Name"].ToString();
comboBox1.Items.Insert(id,name);
}
Always index should start from 0 (Zero).
Easy way to add values to combobox
comboBox1.DataSource=dt;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "ID";
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
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();
}
}
this is my code for multiple value in combobox. I have frmEntryHistory which entry a student id and his/her name in combobox , bookID and the title in combobox, and then date.
im using method on class library to get data from database and store them in dataset. And then i call that method on frmEntryHistory. I can appear ID-Tittle on combobox but not as record just name of columns on master_book table.
Please help me and sorry for confusing english. :)
// Method Library Class
public DataSet getBooks_ComboBox()
{
IDbDataAdapter adapter = null;
DataSet ds = null;
try
{
sb = new StringBuilder();
adapter = new MySqlDataAdapter();
comm = new MySqlCommand();
ds = new DataSet();
openConnection();
comm.Connection = conn;
sb.Append(#"select ID, ID + ' - ' + Title as Book from master_book");
comm.CommandText = sb.ToString();
adapter.SelectCommand = (MySqlCommand)comm;
adapter.Fill(ds);
closeConnection();
return ds;
}
catch (Exception ex)
{
return null;
}
}
//In my form Entry History
private void frmEntryHistory_Load(object sender, EventArgs e)
{
lblTgl.Text = DateTime.Now.ToString("dd/MM/yyyy");
Library lib = new Library();
DataSet ds = new DataSet();
//stored item into combobox
try
{
ds = lib.getBooks_ComboBox();
cmbBook.DataSource = ds.Tables[0];
cmbBook.DisplayMember = "Book";
cmbBook.ValueMember = "ID";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
what i want for output from combobox is ID - Title example : 1 - Novel asd, etc
After you fill the datatable, before you bind it to the combobox, you can create a new column to use. This example uses the pubs database:
DataSet1.titlesDataTable TitlesTable = new DataSet1.titlesDataTable();
titlesTableAdapter1.Fill(TitlesTable);
DataColumn DC = new DataColumn();
DC.ColumnName = "Test";
DC.DataType = typeof(string);
DC.Expression = string.Format("{0} + '-' + {1}", "title_id", "title");
TitlesTable.Columns.Add(DC);
comboBox1.DataSource = TitlesTable;
comboBox1.DisplayMember = "Test";
comboBox1.ValueMember = "title_id";