Windows Develop Bookmark and Share   
 index > Windows Forms Designer > drop down menu in DataGridView
 

drop down menu in DataGridView

I have a dataGridView on my form and it shows three values, which are from a query (not from an automaticly generated dataGrid). I have columns:
- grade
- created date
- teacher
As you can see it shows grades, then a teacher who has entered a particular grade and a date when it`s been entered.
But this Form is for administrator, so he can repair all of these. So I thought it would be good to have at each cell a drop down menu, where the admin can be able to select all whats available:
- grades from 5-10
- changes the date (by clicking on a date cell it opens date time picker
- and in 3rd column (for teachers) it opens a drop down menu with all teachers available.

So, I have started yesterday with the grades, and someone here suggested me this code:
DataGridViewComboBoxColumn col = new
 DataGridViewComboBoxColumn();
for
 (int
 grade = 5; grade <=10; grade++)
{
    col.Items.Add(grade);
}
col.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing; // or ComboBox

this
.dataGridView1.Columns.Add(col);
but it`s not working for me... it does not show the dropdown menu by clicking on a grade cell.

So 1st, where do i need to put this code? maybe into:
private
 void
 dataGridView_CellContentClick(object
 sender, DataGridViewCellEventArgs e)
{  //does the code go here? }

.. or somewhere else?
And sometihng more... in that 1st code for grades, i need to specify sowhere that this is for column "Grade", otherwise how the program will know for which column it is. How to do it?

I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)
  • Moved byOmegaManMVPSunday, May 03, 2009 11:12 AM (From:Visual C# General)
  • Edited byMitja Bonca Friday, May 01, 2009 7:00 PM
  •  
Mitja Bonca  Friday, May 01, 2009 9:29 AM
Can someone please help me out a bit with this?
I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)
Mitja Bonca  Friday, May 01, 2009 6:53 PM
The code you are trying is correct.

Can you post more code.
Thanks, A.m.a.L | [Remember to click "mark as answered" when you get a correct reply to your question]
A.m.a.L - aditi.com - Think Product  Friday, May 01, 2009 7:01 PM
This worked for me: Create the datagridview in design mode with the 3 columns. Then, handle the dataGridView1.DefaultValuesNeeded event. In this, you can add the code:

            DataGridViewComboBoxCell dgvcbc = new DataGridViewComboBoxCell();
            foreach (string name in grades)
            {
                dgvcbc.Items.Add(name);
            }
            e.Row.Cells["Grades"] = dgvcbc;

omarazam  Friday, May 01, 2009 7:03 PM
I can not create it in a desing mode. I did a query (which is very complicated - thats why I use a select statement), but it does not work.
can someone answer me where to put this code, under which method?
I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)
Mitja Bonca  Friday, May 01, 2009 7:21 PM
The code you are trying is correct.

Can you post more code.
Thanks, A.m.a.L | [Remember to click "mark as answered" when you get a correct reply to your question]


Thanks, A.m.a.L | [Remember to click "mark as answered" when you get a correct reply to your question]
A.m.a.L - aditi.com - Think Product  Friday, May 01, 2009 7:28 PM
I have no more code. I am trying to figurate it out why is only this code not showing a drop down menu.
I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)
Mitja Bonca  Friday, May 01, 2009 7:34 PM
it creats a comboBox, but in another column( behind the last - in the code it is missing something that the comboBox will connect to column "Grades"). I have 3 columns in my dataGrid, and the comboBox is the 4th. As i said, I need the connection to Grades, that comboBox will appear for (under Grades) column. This is my code so far:
DataGridViewComboBoxColumn col = new
 DataGridViewComboBoxColumn();
for
 (int
 grade = 5; grade <=10; grade++)
{
    col.Items.Add(grade);
}
col.Width=48
col.Valuemember = "Grades";
col.DisplayMember = "Ocena";
col.DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox;
this.dataGridView1.Columns.Add(col);

What is missing here that the code will connect to Grades columns, and will be added for it?
And Grades - column name is connected with the database table "Grades" - from there the grades are written into dataGrid.
Mitja Bonca  Friday, May 01, 2009 9:47 PM
put this code in the form load, also you don't need

col.Valuemember = "Grades";
col.DisplayMember = "Ocena";

in this case because you generate the value not binding it
Wael Al-Joulani  Saturday, May 02, 2009 6:12 AM
I did put into load_form and it works now. thx
And how do i now save the new selected grade? I will create a new button, when when pressing it, it will save the new selected grade.

I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)
Mitja Bonca  Saturday, May 02, 2009 7:48 AM
Save to database?

Thanks, A.m.a.L | [Remember to click "mark as answered" when you get a correct reply to your question]
A.m.a.L - aditi.com - Think Product  Saturday, May 02, 2009 7:52 AM
Sure, in the dataGrid I have grades, which were inserted through some other form into database. And if I will change a partucular grade, it has ti be saved again somehow.


Mitja Bonca  Saturday, May 02, 2009 7:57 AM
This is what I mean:
Quote:
At point, any changes made by the user in the DataGridView will automically be made to the DataTable, dTable. Now we need a way to get the changes back into the database. All you have to do is call the Update function of the OleDbDataAdapter with the DataTable as the argument to accomplish this.

dAdapter.Update(dTable);
So in my case... I have 1stly need to call the database, then I can save changes, right?
I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)
Mitja Bonca  Saturday, May 02, 2009 8:35 AM
Since your datatable has the updated value which includes your comobobox grad selection.

You can directly use the adapter to update the changes in db.
Thanks, A.m.a.L | [Remember to click "mark as answered" when you get a correct reply to your question]
A.m.a.L - aditi.com - Think Product  Saturday, May 02, 2009 8:42 AM
And how would look the code? never done this before, thats why im askinghow how can I directly use the adapter.


btw, I got an example, and I am wondering from where the "box" value appeared? There is no where defined before this code, and not even in this code. So From where it came? And is not in a default C#`s command base.
code:
	// Set DataGridView Combo Column for CarID field   
	DataGridViewComboColumn ColumnCar = new DataGridViewComboColumn();  
	// DataGridView Combo ValueMember field name is "CarID"  
	// DataGridView Combo DisplayMember field name is "Car"  
	ColumnCar.DataPropertyName = "CarID";  
	ColumnCar.HeaderText = "Car Name";  
	ColumnCar.Width = 80;  
	// Bind ColumnCar to Cars table  
	ColumnCar.box.DataSource = ds.Tables["Cars"];  
	ColumnCar.box.ValueMember = "CarID";  
	ColumnCar.box.DisplayMember = "Car";  
	// Add ColumnCar onto DataGridView layout  
	DataGridView1.Columns.Add(ColumnCar);  

I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)
Mitja Bonca  Saturday, May 02, 2009 8:47 AM
The comboboxx box is bound to ds.Tables["Cars"] . So it will be populated from database.
Thanks, A.m.a.L | [Remember to click "mark as answered" when you get a correct reply to your question]
A.m.a.L - aditi.com - Think Product  Saturday, May 02, 2009 8:49 AM
I see.
But can you please tell me a bit more, on what you said in the previous post: "You can directly use the adapter to update the changes in db."
with some code would be cool
thank you!

I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)
Mitja Bonca  Saturday, May 02, 2009 9:27 AM
try
{
    this.Validate();
    this.yourBindingSource.EndEdit();      this.yourTableAdapter.Update(this.yourDataSet.YourDataTable);
    MessageBox.Show("Update successful");
}
catch (System.Exception ex)
{
    MessageBox.Show("Update failed");
}



Thanks, A.m.a.L | [Remember to click "mark as answered" when you get a correct reply to your question]
A.m.a.L - aditi.com - Think Product  Saturday, May 02, 2009 9:31 AM
thx, but i think I dont have a BindingSourse yet. What is that exactly? is it in my case: ds.Tables["Grade"]
And I would like to save changes back into bd while clicking on button1. Who to do that?
Mitja Bonca  Saturday, May 02, 2009 10:08 AM
The binding source here is your datagrid
Wael Al-Joulani  Saturday, May 02, 2009 11:26 AM
Just gridDataView1, or gridDataview1["Grade"]; ... beacuse the program needs to know from which colums exactly goes.
Ok, but how do i start coding, for using the button1 for saving into db the new value?
Mitja Bonca  Saturday, May 02, 2009 11:32 AM

see this article it will help you to know how to update dataset changes in the database

http://msdn.microsoft.com/en-us/library/system.data.common.dataadapter.update.aspx

Wael Al-Joulani  Saturday, May 02, 2009 11:35 AM
For a query string, what exactly do I need to select before Filling?

this is too damn complicated for me. I`ll never figurate it out.
I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)
Mitja Bonca  Saturday, May 02, 2009 12:20 PM
select the records which you want to be filled in the data grid;
eg: "Select StudentId, StudentName, grade FROM Student";
Wael Al-Joulani  Saturday, May 02, 2009 12:24 PM
So far I have only Grades. So " Select grade from grades";
btw, would you be so kind and help me out how to will this up:
this.Validate();
this.yourBindingSource.EndEdit();
this.yourTableAdapter.Update(this.yourDataSet.YourDataTable);

This upper code i would like to put into private void buttonSave(object sender, EventArgs e)
- is that OK? ----------------------------------------------------------------------------------------------------
The 1st code in the form_Load: DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn(); for (int mygrade = 5; mygrade <=10; mygrade++) { col.Items.Add(mygrade); } col.DataPropertyName = "Grade"; col.HeaderText = "Grade"; col.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing; // or ComboBox this .dataGridView1.Columns.Add(col);
Is this ok? I mean that I have something in a form_Load and the other in the Button1_Click? Because the save have to happen while changing and pressing a "Save" button.

Mitja Bonca  Saturday, May 02, 2009 1:05 PM
you can do the update anyware, it's not necessary to be in the same function, also you can select the grade like you type but the question is why you need to select only the grade in the datagrid?? what is this kind of information will help the viewer if you return just one column in the datagrid?
Wael Al-Joulani  Saturday, May 02, 2009 1:10 PM
Grades are only the 1st value that I want to sort out. I have two others. But I would like to finish 1st the Grades,and then go to othe two. I just dont know how to do a correct code for inserting (saving) the new value.
I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)
Mitja Bonca  Saturday, May 02, 2009 1:13 PM
dataSet will contains all new values from the datagrid so use the same dataset you bind to the datagrid and do the update from the DataAdapter it will save all changes you did to the database
Wael Al-Joulani  Saturday, May 02, 2009 1:18 PM
I am so confused now that I dont knowwhere to start. i got this example:

And i have no where defind "TableAdapter" and "DataTable", and you ae telling me sometihng different.
Is there any example of saving from dataGrid into db? So far i havent seen any, only how to set the comboBox in a dataGrid.
I will really appreciate yif you have any example of it, because as i said, i`m so confused now that i dont know what to use.
thx

I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)
Mitja Bonca  Saturday, May 02, 2009 1:29 PM
Wael Al-Joulani  Saturday, May 02, 2009 1:31 PM
This is all my code so far for this (but don`t be scared, because it is in slovenian language):

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Data.SqlClient;

namespace seminarska4

{

public partial class PregledOsebja : Form

{

SqlConnection povezava;

public PregledOsebja()

{

InitializeComponent();

}

private void PregledOsebja_Load(object sender, EventArgs e)

{

string p = @"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Informatika\PRO2\Seminarska4\baza_NET.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True" ;

povezava = new SqlConnection (p);

comboBoxOsebje.Items.Add("Študenti" );

comboBoxOsebje.Items.Add("Učitelji" );

listBoxIzbira.Visible = false ;

dataGridView1.Visible = false ;

dataGridView1.RowHeadersVisible = false ;

// 1. Combobox in dataGridView for Ocena (eng-Grade):

DataGridViewComboBoxColumn ocena = new DataGridViewComboBoxColumn ();

for (int grade = 5; grade <= 10; grade++)

{

ocena.Items.Add(grade);

}

ocena.DataPropertyName = "Ocena" ;

ocena.HeaderText = "Ocena" ;

ocena.Width = 48;

ocena.DisplayStyle = DataGridViewComboBoxDisplayStyle .Nothing;

this .dataGridView1.Columns.Add(ocena);

// 2. Combobox in dataGridView for ime (eng-Student`s name):

// DataGridViewComboBoxColumn ime = new DataGridViewComboBoxColumn();


// 3. Combobox in dataGridView for DatumVnosa (eng-Insert date):

// DataGridViewComboBoxColumn DatumVnosa = new DataGridViewComboBoxColumn();

}

private void buttonShrani_Click(object sender, EventArgs e)

{

DataSet dataset = new DataSet ();

povezava.Open();

SqlDataAdapter adapter = new SqlDataAdapter ();

string poizvedba = "SELECT Ocena FROM Ocene" ; //Select Grade From Grades"

adapter.SelectCommand = new SqlCommand (poizvedba, povezava);

SqlCommandBuilder builder = new SqlCommandBuilder (adapter);

adapter.Fill(dataset);

//HERE GOES THE CODE?? what code?

adapter.UpdateCommand = builder.GetUpdateCommand();

adapter.Update(dataset);

povezava.Close();

//return dataset;

}

}

}

Would you take a look at this code and tell me what do to more? How to do code for saving back into db.



I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)
Mitja Bonca  Saturday, May 02, 2009 1:41 PM
This is my last code, but I dont know what to fill for TableAdapter and some more thing there. And thats because I didnt automaticly fill the dataGrid. Can someone fix it:

private void buttonShrani_Click(object sender, EventArgs e)

{

povezava.Open();

SqlDataAdapter dataAdapter = new SqlDataAdapter ();

string poizvedba = "SELECT Ocena FROM Ocene" ;

dataAdapter.SelectCommand = new SqlCommand (poizvedba, povezava);

SqlCommandBuilder commBuilder = new SqlCommandBuilder (dataAdapter);

DataSet dataSet = new DataSet ();

adapter.Fill(dataSet);

ocena.DataSource = dataSet.Tables["Ocena" ];

try

{

this .Validate();

this .dataGridView1.EndEdit();

this .yourTableAdapter.Update(this .yourDataSet.YourDataTable);

MessageBox .Show("Update successful" );

}

catch (System.Exception ex)

{

MessageBox .Show("Update failed" );

}

adapter.UpdateCommand = builder.GetUpdateCommand();

adapter.Update(dataset);

povezava.Close();

//return dataset;

}



I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)
Mitja Bonca  Saturday, May 02, 2009 2:23 PM
No one wouldnt know? please. I`m stuck here. Just a bit of a help.

I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)
Mitja Bonca  Saturday, May 02, 2009 4:16 PM

this.dataGridView1.EndEdit();

this.yourTableAdapter.Update(this.yourDataSet.YourDataTable);

What to do in case that I don`t have a tableAdapter? What to do then? Insteda od table adapter I have a query ( an sql statement, which get the required filds out of the database). And what would be the "yourDataSet" and "YourDataTable" in my case?

This is my 1st time that I`ve experianced to work and changing dataGrid. So, I would really appreciate some help! I know you guys can help me. Thx


I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)
Mitja Bonca  Saturday, May 02, 2009 7:12 PM
yourtableAdapter means DataAdapter
"yourDataSet" in your case is "dataSet"
"YourDataTable" is "dataSet.Tables[0]"
this .yourTableAdapter.Update(this .yourDataSet.YourDataTable);
this.dataadapter.Update(this.dataSet.Tables[0]);
Wael Al-Joulani  Sunday, May 03, 2009 7:27 AM
Thnk you very much for explanation.
One moer question, what would be wrong if I wouldn`t write this . infront yourTabe, yourData,..)
Because dataAdapte, dataSet are not available if I start with this .
Otherwise, they are available, if i start directly with dataAdapter and dataSet.

I have all this in try, catch, but even if i put the code outside that i dont have available dataAdpater and dataSet if I start with
this .
You have any clue why I dont have it?
This is my code, what could be wrong:

SqlDataAdapter dataAdapter = new SqlDataAdapter();
string poizvedba = "SELECT Ocena FROM Ocene";
DataTable dataTable=new DataTable();
dataAdapter.SelectCommand = new SqlCommand(poizvedba, povezava);
SqlCommandBuilder commBuilder = new SqlCommandBuilder(dataAdapter);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
dataGridView1.DataSource = dataTable;
try
{
Validate();
dataGridView1.EndEdit();
dataAdapter.Update(dataSet.Tables["Ocena"]);
MessageBox.Show("Update successful");
}
catch (System.Exception ex)
{
MessageBox.Show("Update failed");
}

.. btw, it`s not working, when with debug comes to this line "
dataAdapter.Update(dataSet.Tables["Ocena"]);", it goes then to catch. Dont know why.


I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)
Mitja Bonca  Sunday, May 03, 2009 9:34 AM
you can write it without this because you write it within {}, another thing here it's seems you didn't update the values of the dataset here so wan't to update nothing and you missed to insert the update command statement before you trying to update "dataAdapter.UpdateCommand = commBuilder.GetUpdateCommand()" if you just want to update and add "dataadapter.InsertCommend = commBuilder.GetInsertCommand()" if you want to add new records to the data base
Wael Al-Joulani  Sunday, May 03, 2009 9:42 AM
so it should look like this?:
SqlDataAdapter dataAdapter = new SqlDataAdapter();
string poizvedba = "SELECT Ocena FROM Ocene";
DataTable dataTable=new DataTable();
dataAdapter.SelectCommand = new SqlCommand(poizvedba, povezava);
SqlCommandBuilder commBuilder = new SqlCommandBuilder(dataAdapter);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
dataAdapter.InsertCommand = commBuilder.GetInsertCommand();
dataAdapter.UpdateCommand = commBuilder.GetUpdateCommand();
dataGridView1.DataSource = dataTable;
try
{
Validate();
dataGridView1.EndEdit();
dataAdapter.Update(dataSet.Tables["Ocena"]);
MessageBox.Show("Update successful");
}
catch (System.Exception ex)
{
MessageBox.Show("Update failed");
}

it throws an error at updateCommand:
Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.

I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)
Mitja Bonca  Sunday, May 03, 2009 10:43 AM

this error occured becaue you didn't retrieve the primary key from the data base, if you have it return it in the select statement

Wael Al-Joulani  Sunday, May 03, 2009 10:46 AM
I put id into select:"string poizvedba = "SELECT IDOcene, Ocena FROM Ocene";"

but again throws a system error: Value can not be null. Parameter name: dataTable.
This throws:
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Update failed");
}


I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)
Mitja Bonca  Sunday, May 03, 2009 11:04 AM
try this

in the Fill and update add the table name
dataAdapter.Fill(dataSet,"Ocena");
Wael Al-Joulani  Sunday, May 03, 2009 11:07 AM
the probelm is becuaseDataTable dataTable=new DataTable(); is null, if I go with the mouse over in he debug mode, I see only "{}". This isnt so good right? What should be written into it?
I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)
Mitja Bonca  Sunday, May 03, 2009 1:54 PM
and this: I have updated my query with all three values:string poizvedba = "SELECT Ocene.Ocena, Študenti.Ime, Prijava.DatumPrijave FROM Ocene, Študenti, Prijava, Učitelji, Predmeti " +
"WHERE Učitelji.Ime = '" + listBoxOsebje.GetItemText(listBoxOsebje.SelectedItem) + "'" +
"AND Predmeti.ImePredmeta = '" + listBoxIzbira.GetItemText(listBoxIzbira.SelectedItem) + "'";
and in the line:
dataAdapter.InsertCommand = commBuilder.GetInsertCommand();
I got en error:Dynamic SQL generation is not supported against multiple base tables.

I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)
Mitja Bonca  Sunday, May 03, 2009 2:17 PM
you cant update or insert by usin gmultiple table you should return the data from one table to do that
Wael Al-Joulani  Sunday, May 03, 2009 2:47 PM
So one step at the time?
I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)

But why this code doesn`t do the insertion? :

SqlDataAdapter dataAdapter = new SqlDataAdapter();
string poizvedba = "SELECT Ocena FROM Ocene";
DataTable dataTable=new DataTable();
dataAdapter.SelectCommand = new SqlCommand(poizvedba, povezava);
SqlCommandBuilder commBuilder = new SqlCommandBuilder(dataAdapter);
DataSet dataSet = new DataSet();
dataGridView1.DataSource = dataTable;
dataAdapter.Fill(dataTable);
dataAdapter.InsertCommand = commBuilder.GetInsertCommand();
dataAdapter.UpdateCommand = commBuilder.GetUpdateCommand();
try
{
Validate();
dataGridView1.EndEdit(); // HERE is empty!
dataAdapter.Update(dataTable);
//dataAdapter.Update(dataTable);
dataTable.AcceptChanges();
MessageBox.Show("Update successful");


One more thing,DataTable dataTable=new DataTable(); is null - this isn`t so good either, right?

You know what could be the problem, I fill my dataGrid with a query (select statement) - which is consisted from three tables. This is maybe the issue here, why it can`t read the dataGridView1. What do you think?


Sorry for being so annoyed, but there is my 1st time doing this. But I would like to learn. Still new to this thing :)


Mitja Bonca  Sunday, May 03, 2009 8:38 PM
use the dataSet instead of dataTable, define the dataset,dataadapter,connection and select commandas global variables (outside any function and within the class), in the form load fill the dataset and assign it to the datagrid, add new button to update data and within it's click event add the update lines

connection.Open();
dataAdapter.InsertCommand = commBuilder.GetInsertCommand();
dataAdapter.UpdateCommand = commBuilder.GetUpdateCommand();
Validate();
dataGridView1.EndEdit();
dataSet.Tables["Ocena"].AcceptChanges();
dataAdapter.Update(dataSet,"Ocena");
MessageBox.Show("Update successful");
connection.Close();
Wael Al-Joulani  Monday, May 04, 2009 5:44 AM
I did what you just said, but when it comes to "dataSet.Tables["Ocena"].AcceptChanges();" goes to catch and throws an error: Object reference not set to an instance of an object.
What could be wrong - there is no connection somewhere?

I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)
Mitja Bonca  Monday, May 04, 2009 8:45 AM
did you fill the dataSet istead of the datatable, also where you initialize the dataSet? in the form load or where you define it in the global?
Wael Al-Joulani  Monday, May 04, 2009 8:49 AM
Yes, I filled the dataSet. I dont even have dataTable.
I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)

I defind DataSet, SqlDataAdapter, SclCommBuilder, SqlConnection out side on any function - as you told me to do.

This is what I have in the form load:
string poizvedba = "SELECT IDOcene, Ocena FROM Ocene";
dataSet = new DataSet();
dataAdapter = new SqlDataAdapter();
commBuilder = new SqlCommandBuilder(dataAdapter);
dataAdapter.SelectCommand = new SqlCommand(poizvedba, povezava);
dataAdapter.Fill(dataSet);
dataGridView1.DataSource = dataSet;

and this I have in the button click:
povezava.Open();
dataAdapter.InsertCommand = commBuilder.GetInsertCommand();
dataAdapter.UpdateCommand = commBuilder.GetUpdateCommand();
try
{
Validate();
dataGridView1.EndEdit();
dataSet.Tables["Ocena"].AcceptChanges();
dataAdapter.Update(dataSet, "Ocena");
MessageBox.Show("Update successful");
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Update failed");
}
povezava.Close();
Mitja Bonca  Monday, May 04, 2009 8:58 AM
so where you in initialise the dataset? you should inistialize it in the global

DataSet dataset = new DataSet();
Wael Al-Joulani  Monday, May 04, 2009 9:02 AM
I did like this:
out side of any function I did:
DataSet dataSet;

then in the form load I did

dataSet = new DataSet(); - I think this is the same way.
But I am worring that dataGridView1 is a problem
Because it is consisted from 3 values and all those three are from "manual" query : which is:
// - my query: SELECT Grades.Grande, Grades.EntryDate, Teachers.Name, FROM Grandes, Subjects, Students, Login, Program, Teachers

string ocenePredmeta = "SELECT Ocene.Ocena, Ocene.DatumVnosa, Učitelji.Ime FROM Ocene, Predmeti, Študenti, Prijava, Program, Učitelji WHERE " +
"Predmeti.IDPredmeta=Prijava.IDPredmetaFK AND Študenti.IDŠtudenta=Prijava.IDŠtudentaFK " +
"AND Prijava.IDPrijave=Ocene.IDPrijaveFK AND Študenti.Ime = @imeŠtudenta " +
"AND Predmeti.ImePredmeta = @imePredmeta " +
"AND Učitelji.IDUčitelja = Program.IDUčiteljaFK " +
"AND Program.IDPrograma = Ocene.IDProgramaFK";
SqlCommand cmd4 = new SqlCommand();
SqlParameter param4 = new SqlParameter();
SqlParameter param5 = new SqlParameter();
param4.ParameterName = "@imeŠtudenta";
param5.ParameterName = "@imePredmeta";
param4.Value = listBoxOsebje.GetItemText(listBoxOsebje.SelectedItem);
param5.Value = listBoxIzbira.GetItemText(listBoxIzbira.SelectedItem);
cmd4.Parameters.Add(param4);
cmd4.Parameters.Add(param5);
cmd4.Connection = povezava;
cmd4.CommandText = ocenePredmeta;
cmd4.CommandType = CommandType.Text;
povezava.Open();

//VNOS V DATA GRID VIEW ŠTUDENTI:
SqlDataReader bralec4 = cmd4.ExecuteReader();
DataTable table = new DataTable();
table.Load(bralec4);
bralec4.Close();
dataGridView1.DataSource = table;
//dataGridView1.Columns["Ocena"].Width = 48; - širina je definirana že v form_Load!
dataGridView1.Columns["DatumVnosa"].Width = 90;
povezava.Close();
dataGridView1.Visible = true;
Mitja Bonca  Monday, May 04, 2009 9:03 AM
Damn, I just noticed... I use here DataTable in this query, is this the problem?
I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)
Mitja Bonca  Monday, May 04, 2009 9:09 AM
no it's not the same, when wou initialize any value inside the function this initialization will be within the same function and you should re-Initiaized it in every function you use it, but if you in initialzed it in the global this will let him open
Wael Al-Joulani  Monday, May 04, 2009 9:09 AM
This:dataSet.Tables["Ocena"].AcceptChanges();
Is Ocena a Table or column name?
Because in my case "Ocena" is a column name, on the same level as IDOcene (IDGrade - eng).
If you look at my query in form load:
"SELECT IDOcene, Ocena FROM Ocene"; What do I need to use in:

dataSet.Tables["???"].AcceptChanges();
dataAdapter.Update(dataSet, "???");
Mitja Bonca  Monday, May 04, 2009 9:16 AM
Sory I mean Ocene from "SELECT IDOcene, Ocena FROM Ocene"
Wael Al-Joulani  Monday, May 04, 2009 9:33 AM
I the form load in these lines:
dataAdapter.Fill(dataSet);
dataGridView1.DataSource = dataSet.;
I changed into:
dataAdapter.Fill(dataSet.Tables["Ocene.Ocena"]); //or just ["Ocene"]
dataGridView1.DataSource = dataSet.Tables["Ocene.Ocena"]; //or just ["Ocene"]

But all is Null! Why? This is the probelm - it doesn`t read or fill.

I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)
Mitja Bonca  Monday, May 04, 2009 9:36 AM
just use
dataAdapter.Fill(dataSet.Tables["Ocene"]);
dataGridView1.DataSource = dataSet.Tables["Ocene"];
Wael Al-Joulani  Monday, May 04, 2009 9:41 AM
if you still have error, can youupload your projectsome where to check it and return it to you??
Wael Al-Joulani  Monday, May 04, 2009 9:43 AM
you can also use the wizard instead of do it by code, wou can add DataSets by right click on the solution -> AddItem -> DataSet

then in the dataSet right click AddDataTable then follow the wizard, this will create every thing fr you
now just addyour newdataset and DataAdapter from the listBox (they will appear after build your application)

now from the properties of the grid view select the dataSorce and datamember then edit the column and select the column tyoe you want (if you want to change it to combobox)

fill the dataset in the form load and in the update button update it, this will be work fine for you
Wael Al-Joulani  Monday, May 04, 2009 10:11 AM
I have uploaded the file into my forum. Just scroll down to English zone, and click on Computers&Internet. Inside you will find the zip file in the C# thread.
thx mate. I appreciate your effort.

I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)
Mitja Bonca  Monday, May 04, 2009 10:17 AM
ok thnx
in the form load remove the two line which set the visibility of the grid view to be false;
replace dataAdapter.Fill(dataSet.Tables["Ocene.Ocena"]); with dataAdapter.Fill(dataSet,"Ocene");
And dataGridView1.DataSource = dataset.Tables["Ocene.Ocena"]; with And dataGridView1.DataSource = dataset.Tables["Ocene"]

that work fine with me
Wael Al-Joulani  Monday, May 04, 2009 10:39 AM
for the update button change the dataAdapter.Update(dataSet); with dataAdapter.Update(dataSet,"Ocene");
Wael Al-Joulani  Monday, May 04, 2009 10:46 AM
Ok, thank you very much. Will do this a bit later. Have to go now - school time (at 29years of age :) ).
Will let you know if it works for me too. But I`m sure it will.
bye, bye

I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)
Mitja Bonca  Monday, May 04, 2009 10:47 AM
Now I got the table "Ocene" into dataGridView1.DataSource = dataSet.Tables["Ocene"];

but when the code comes todataAdapter.Update(dataSet.Tables["Ocene"]); - and I put this line into immediate window I got "0". This is not right. it should be 1 - one table updated - I think.
The code comes to an end with no errors, and in the dataGrid "Ocena" is now the new grade, but when I go out of this window and back in is there again the old grade. That means it does not change. Any idea why?

And in the click button is this line ok?dataSet.Tables["Ocene"].AcceptChanges(); ?
Mitja Bonca  Monday, May 04, 2009 1:56 PM

debug you application and trace it to the line after dataAdapter.InsertCommand = commBuilder.GetInsertCommand(); and dataAdapter.UpdateCommand = commBuilder.GetUpdateCommand(); , then check what is the insert and update command text, maybe it's wrong.

Wael Al-Joulani  Tuesday, May 05, 2009 5:43 AM
In the InsertCommandText: "INSERT INTO [Ocene] ([IDOcene], [Ocena]) VALUES (@p1, @p2)"
in the UpdateCommandText: "UPDATE [Ocene] SET [IDOcene] = @p1, [Ocena] = @p2 WHERE (([IDOcene] = @p3) AND ([Ocena] = @p4))"


Everything what is written in the immediate window:

commBuilder.GetInsertCommand();
{System.Data.SqlClient.SqlCommand}
base {System.Data.Common.DbCommand}: {System.Data.SqlClient.SqlCommand}
CommandText: "INSERT INTO [Ocene] ([IDOcene], [Ocena]) VALUES (@p1, @p2)"
CommandTimeout: 30
CommandType: Text
Connection: {System.Data.SqlClient.SqlConnection}
DesignTimeVisible: true
Notification: null
NotificationAutoEnlist: false
Parameters: {System.Data.SqlClient.SqlParameterCollection}
Transaction: null
UpdatedRowSource: None

commBuilder.GetUpdateCommand();
{System.Data.SqlClient.SqlCommand}
base {System.Data.Common.DbCommand}: {System.Data.SqlClient.SqlCommand}
CommandText: "UPDATE [Ocene] SET [IDOcene] = @p1, [Ocena] = @p2 WHERE (([IDOcene] = @p3) AND ([Ocena] = @p4))"
CommandTimeout: 30
CommandType: Text
Connection: {System.Data.SqlClient.SqlConnection}
DesignTimeVisible: true
Notification: null
NotificationAutoEnlist: false
Parameters: {System.Data.SqlClient.SqlParameterCollection}
Transaction: null
UpdatedRowSource: None
Mitja Bonca  Tuesday, May 05, 2009 8:35 AM
remove dataSet.AcceptChanges();
Wael Al-Joulani  Tuesday, May 05, 2009 9:53 AM
I did, and its the same. Doesn˙t update. Is there everytihng OK in the Insert and Update? Why isUpdatedRowSource: None?
I really dont understand whats wrong that it does not update.
Mitja Bonca  Tuesday, May 05, 2009 10:30 AM
strange, I write the same code in application and it's wotk fine for me, it's update and insert values either the UpdatedRowSource: None
Wael Al-Joulani  Tuesday, May 05, 2009 10:49 AM
can you upload somewhere ur code then? Maybe I am missing something out here. thx


I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)
Mitja Bonca  Tuesday, May 05, 2009 11:30 AM
SqlConnection povezava;
        DataSet dataSet;
        SqlDataAdapter dataAdapter;
        SqlCommandBuilder commBuilder;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string p = "Data Source=sqlserver;Initial Catalog=Wael;User ID=sa;Password=sa";
            povezava = new SqlConnection(p);

            comboBox1.Items.Add("Student");
            comboBox1.Items.Add("Ueitel");
             //Combobox v dataGridView za OCENA - in izbira vseh mo‍nih ocen:           

            DataGridViewComboBoxColumn ocena = new DataGridViewComboBoxColumn();
            for (int grade = 5; grade <= 10; grade++)
            {
                ocena.Items.Add(grade);
            }
           ocena.DataPropertyName = "Ocena";
           ocena.HeaderText = "Ocena";
           ocena.Width = 48;
           ocena.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
           this.dataGridView1.Columns.Add(ocena);

           string poizvedba = "SELECT ItemNumber,ItemName FROM Items";
           dataSet = new DataSet();
           dataAdapter = new SqlDataAdapter();
           
           commBuilder = new SqlCommandBuilder(dataAdapter);
           dataAdapter.SelectCommand = new SqlCommand(poizvedba, povezava);
           dataAdapter.Fill(dataSet, "Items");
           dataGridView1.DataSource = dataSet.Tables["Items"]; 
        }

        private void button1_Click(object sender, EventArgs e)
        {
            dataAdapter.InsertCommand = commBuilder.GetInsertCommand();
            dataAdapter.UpdateCommand = commBuilder.GetUpdateCommand();
            try
            {
                Validate();
                dataGridView1.EndEdit();
                dataAdapter.Update(dataSet,"Items");
                //dataAdapter.Update(dataSet, "Ocena");
                MessageBox.Show("Update successful");
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message, "Update failed");
            }
            povezava.Close();
        }
that all the code i used
Wael Al-Joulani  Tuesday, May 05, 2009 11:33 AM
You know what can be the problem. I have a separated query which writes out the grande... one if for students (študenti) and another for teachers (učitelji). This code below gets the values from the database, and write them into dataGrid. Maybe is this the problem - maybe is does not allow to change later somehow - I dont know.

In the comboBox the user choose either "Teachers" or or either "Students".
Then in 1st listBox appear all teachers (if theachers choosen) or all students (if students choosen).
Then in 2nd list box appear Subject that a particular teacher or student has.
And when the user selects a particular subject, in the dataGridView he sees what is down in the code:

From SELECT query:
Students (Grade, EntryDate, Techer)
Teachers:(Student, LoginDate, Grade)

if (comboBoxOsebje.GetItemText(comboBoxOsebje.SelectedItem) == "Študenti")
{
string ocenePredmeta = "SELECT Ocene.Ocena, Ocene.DatumVnosa, Učitelji.Ime FROM Ocene, Predmeti, Študenti, Prijava, Program, Učitelji WHERE " +
"Predmeti.IDPredmeta=Prijava.IDPredmetaFK AND Študenti.IDŠtudenta=Prijava.IDŠtudentaFK " +
"AND Prijava.IDPrijave=Ocene.IDPrijaveFK AND Študenti.Ime = @imeŠtudenta " +
"AND Predmeti.ImePredmeta = @imePredmeta " +
"AND Učitelji.IDUčitelja = Program.IDUčiteljaFK " +
"AND Program.IDPrograma = Ocene.IDProgramaFK";
SqlCommand cmd4 = new SqlCommand();
SqlParameter param4 = new SqlParameter();
SqlParameter param5 = new SqlParameter();
param4.ParameterName = "@imeŠtudenta";
param5.ParameterName = "@imePredmeta";
param4.Value = listBoxOsebje.GetItemText(listBoxOsebje.SelectedItem);
param5.Value = listBoxIzbira.GetItemText(listBoxIzbira.SelectedItem);
cmd4.Parameters.Add(param4);
cmd4.Parameters.Add(param5);
cmd4.Connection = povezava;
cmd4.CommandText = ocenePredmeta;
cmd4.CommandType = CommandType.Text;
povezava.Open();

//DATA GRID VIEW STUDENTS:
SqlDataReader bralec4 = cmd4.ExecuteReader();
DataTable table = new DataTable();
table.Load(bralec4);
bralec4.Close();
dataGridView1.DataSource = table;
//dataGridView1.Columns["Ocena"].Width = 48; - širina je definirana že v form_Load!
dataGridView1.Columns["DatumVnosa"].Width = 90;
povezava.Close();
dataGridView1.Visible = true;
}

else if (comboBoxOsebje.GetItemText(comboBoxOsebje.SelectedItem) == "Učitelji")
{
string oceneŠtudenta = "SELECT Študenti.Ime, Prijava.DatumPrijave, Ocene.Ocena FROM Študenti, Učitelji, Predmeti, Prijava, Program, Ocene " +
"WHERE Študenti.IDŠtudenta = Prijava.IDŠtudentaFK AND Predmeti.IDPredmeta = Prijava.IDPredmetaFK " +
"AND Prijava.IDPrijave = Ocene.IDPrijaveFK " +
"AND Program.IDPrograma = Ocene.IDProgramaFK " +
"AND Učitelji.Ime = @imeUčitelja " +
"AND Predmeti.ImePredmeta = @imePredmeta";
SqlCommand cmd7 = new SqlCommand();
SqlParameter param7 = new SqlParameter();
SqlParameter param7_2 = new SqlParameter();
param7.ParameterName = "@imeUčitelja";
param7_2.ParameterName = "@imePredmeta";
param7.Value = listBoxOsebje.GetItemText(listBoxOsebje.SelectedItem);
param7_2.Value = listBoxIzbira.GetItemText(listBoxIzbira.SelectedItem);
cmd7.Parameters.Add(param7);
cmd7.Parameters.Add(param7_2);
cmd7.Connection = povezava;
cmd7.CommandText = oceneŠtudenta;
cmd7.CommandType = CommandType.Text;
povezava.Open();

SqlDataReader bralec7 = cmd7.ExecuteReader();
DataTable table2 = new DataTable();
table2.Load(bralec7);
bralec7.Close();
dataGridView1.DataSource = table2;
//dataGridView1.Columns["Ocena"].Width = 48;
dataGridView1.Columns["DatumPrijave"].Width = 90;

povezava.Close();
dataGridView1.Visible = true;
}

Do you think this could have something to do with it?

If you would like to test whole code of this form it`s HERE! On the same place as yesterday.

I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)
Mitja Bonca  Tuesday, May 05, 2009 11:46 AM
btw, what exactly in the code bellow reads the news inserted value and what the new value updates. I am not an expert, but does all these do: ?

dataAdapter.InsertCommand = commBuilder.GetInsertCommand();
dataAdapter.UpdateCommand = commBuilder.GetUpdateCommand();
And ehat is this code for exactly:
Validate();
dataGridView1.EndEdit();
dataSet.Tables["Ocene"].AcceptChanges(); //This what says immediate window here:Expression has been evaluated and has no value
dataAdapter.Update(dataSet, "Ocene");

Bucause there nothing on the end of this code, I mean, even if I do a change, this change does not appear in the upper code.
Mitja Bonca  Tuesday, May 05, 2009 12:44 PM
the new and changed values will be found in the data set, the insertcommand and update command tells the data adapter what is the insert and update statement with it's parameters to execute it when you run the dataAdapter.Update(dataSet,"TableName");

validate(); check the form data
datagridview.EndEdit() tills the grid that you finishedyour changes
dataSet.Tables["Ocene"].AcceptChanges(); // tells the dataset to save the new values, this will return the original data if you put it before Update adapter
dataAdapter.Update(dataSet, "Ocene"); // save the new values from the data set into the database
Wael Al-Joulani  Tuesday, May 05, 2009 1:10 PM
I inserted another comboBoxColumn StudentsNames and now the Grades are not working - can not select them any more. Damn strange.
Can I ask you, if you would be so kind, I will give you my whole project and will take a look whats all about. Cause this way I am sure I wont salve the problem.
The project is uploaded (Seminarska5.32.zip file), together with the database, you can get it HERE (on my webiste`s forum - on english zone).

When you will have the project opened, open the form "PregledOsebja" - there is the code we are discussing for a couple of days. And it is a child form of Form9_admin!
the name and a password to come into administrator`s area is "a" and "a" (you can check in a db table admin). When you will open the admin form, click on Začetek/Pregled osebja.

If you are so kind, I will really appreciate it. Cause it seems I`m stuck here - newbies you know :)
Thank you in advance!


I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)
Mitja Bonca  Tuesday, May 05, 2009 1:50 PM
Look, let`s forget about all this mess.
I have created a data table which in my case is consisted by:
- Student name
- Entry date
- Grade
I have put it into a dataGridView1. But there are now all selected items.
I have a question now, how this dataGrid connect to a listBoxTeachers and listBoxSubjects? The thing is, I would like to select a teacher, then a subject (that has this teacher) and then in a dataGrid will be shown the data table I just created (i have already created queries for selecting teacher and subjects).

Simple explanation: When selecting a Teacher in 1st listBox it appears the 2nd listBox. Then in the 2nd listBox you select a Subject and then dataGrid appears with the students, who have grades at the selected Teacher and selected Subject.


I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)
Mitja Bonca  Tuesday, May 05, 2009 7:06 PM
in the form load fill the listBoxTeachers, then in the selectedIndexchanged for this listbox fill the listBoxSubjects and fill the grid in the subject listBox selcted indexchange
(you should use where clause in the select statement for both subject list box and grid filling)
Wael Al-Joulani  Wednesday, May 06, 2009 5:59 AM
I dont understand your statement in the brackets.
I already have the listBoxes working. All I need is a select statement which isconnected to dataGrid, am I right?

I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)
Mitja Bonca  Wednesday, May 06, 2009 6:55 AM
If your list box filtered as you want and you just want to fill the datagrid with this result
so you are right.
just fill the grid with the select statement

eg: "SELECT ocenaID,Ocena FROM Ocene WHERE OceneID = + " listbox1.SelectedValue
Wael Al-Joulani  Wednesday, May 06, 2009 9:00 AM
I did now sometihng different. Did my own dataSet, and changed the code for it, but again it doesn`t change the value:

private void PregledOsebja_Load(object sender, EventArgs e)
{
this.imeŠtudenta_DatumVnosa_OcenaTableAdapter.Fill(this.dataSet1.ImeŠtudenta_DatumVnosa_Ocena);
string p = @"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Informatika\PRO2\Seminarska4\baza_NET.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
povezava = new SqlConnection(p);

comboBoxOsebje.Items.Add("Študenti");
comboBoxOsebje.Items.Add("Učitelji");
listBoxIzbira.Visible = false;
dataGridView1.Visible = false;
dataGridView1.RowHeadersVisible = false;


//
//COMBOBOX ZA STOLPEC "Ocene.Ocena" V dataGridView1 in IZBIRA VSEH OCEN:
//
dataGridView1.AutoGenerateColumns = false;

string poizvedba = "SELECT IDOcene, Ocena FROM Ocene";
//dataSet = new DataSet();
dataAdapter = new SqlDataAdapter();
commBuilder = new SqlCommandBuilder(dataAdapter);
dataAdapter.SelectCommand = new SqlCommand(poizvedba, povezava);
dataAdapter.Fill(dataSet1, "Ocene");
dataGridView1.DataSource = dataSet1.Tables["Ocene"];
DataGridViewComboBoxColumn ocena = new DataGridViewComboBoxColumn();
for (int grade = 5; grade <= 10; grade++)
{
ocena.Items.Add(grade);
}
//ocena.DataSource = dataSet.Tables["Ocene"];
ocena.DataPropertyName = "Ocena";
ocena.HeaderText = "Ocena";
ocena.Width = 60;
ocena.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
dataGridView1.Columns.Add(ocena);
}

private void buttonShrani_Click(object sender, EventArgs e)
{
povezava.Open();
dataAdapter.InsertCommand = commBuilder.GetInsertCommand();
dataAdapter.UpdateCommand = commBuilder.GetUpdateCommand();
try
{
Validate();
dataGridView1.EndEdit();
dataAdapter.Update(dataSet1.Tables["Ocene"]);// To here it even doesn`t come any new value
dataSet1.Tables["Ocene"].AcceptChanges();
MessageBox.Show("Update successful");
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Update failed");
}
povezava.Close();
}

This is what I got written out at line: DataAdapter.InsertCommand = commBuilder.GetInsertCommand();
{System.Data.SqlClient.SqlCommand}
base {System.Data.Common.DbCommand}: {System.Data.SqlClient.SqlCommand}
CommandText: "INSERT INTO [Ocene] ([IDOcene], [Ocena]) VALUES (@p1, @p2)"
CommandTimeout: 30
CommandType: Text
Connection: {System.Data.SqlClient.SqlConnection}
DesignTimeVisible: true
Notification: null
NotificationAutoEnlist: false
Parameters: {System.Data.SqlClient.SqlParameterCollection}
Transaction: null // ??
UpdatedRowSource: None // ??I would say this is not ok. What so you think?

BTW: I got an example of this, and there is shown that if you want to change the previous value with new value, you 1st need to delete the old one, and then insert the new one.
Or is this not correct?
Cause this my code above is obviously not working.
Mitja Bonca  Wednesday, May 06, 2009 11:38 AM
Hi there Wael, are you still willing to help me out a bit?
I have found out that I have a total mess in my code, and so far nothing seemed to work. So I need to start from a scratch.

- I have created a dataSet1 - this fills up my dataGrid (Ocene, DatumVnosa, Študent - eng: Grades, EntryDate, Student) - OK!
- At colums "Ocene" I would like to put a comboBox (while clicking on a particular cell in the column Ocene, it will open a drop down menu with grades from 5-10).
- While selecting another grade from a drop down menu, and clicking on a button Save, the new selected value replaces the old one in the database - this is the most important thing - How to do coding for to remove the old and replace it with the new selected grade?



I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)
Mitja Bonca  Thursday, May 07, 2009 7:35 AM

Hi Mitja,

> How to do coding for to remove the old and replace it with the new selected grade?

Use TableAdapter or DataAdapter to save changes back to DB. Please read the following MSDN documents on how to configurate data adapters or table adapters.

"Data Adapter Configuration Wizard"
http://msdn.microsoft.com/en-us/library/kb6bw5z5(VS.71).aspx

"How to: Create TableAdapters"
http://msdn.microsoft.com/en-us/library/6sb6kb28(VS.80).aspx

Hope this helps.

Sincerely,
Linda Liu

Linda Liu  Thursday, May 07, 2009 8:20 AM
Not much, I am still a beginner, so it would be good to have an example.

this is my code for having grades from 5 to 10 in the column " Ocene" (eng:grades)

DataGridViewComboBoxColumn ocena = new DataGridViewComboBoxColumn();
for (int grade = 5; grade <= 10; grade++)
{
ocena.Items.Add(grade);
}
ocena.DataPropertyName = "Ocena";
ocena.HeaderText = "Ocena";
ocena.Width = 60;
ocena.MaxDropDownItems = 6;
ocena.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
dataGridView1.Columns.Add(ocena);

So, how to do other code for select, insert and update? I have it, but it obviously not working.

I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)
Mitja Bonca  Thursday, May 07, 2009 8:48 AM
I would need to use "ocena" or "grade" from the code above to fill the dataAdapter.
As far as I know: the code above generates intigers from 5 to 10. So while I select one from a dropDown menu, this number has to fill filled somehow and then saved back into database. Dont you agree?

I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)
Mitja Bonca  Thursday, May 07, 2009 11:15 AM
Wael, I have one more question for you... if you remember, the app did work for you, but for me it didn`t.
I have two foreign keys in the table "Ocene", so is it possible that this was the reason for not working properly?

If table Grades I have:IDGrade, IDLoginFK, IDProgramFK, Grade, EntryDate (FK are foreign keys to two other tables). Could this be the reason?

I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)
Mitja Bonca  Thursday, May 07, 2009 12:08 PM
I don't think that the foreign key is the reason if it's allow null, otherwise it will return an error
Wael Al-Joulani  Thursday, May 07, 2009 2:02 PM
thx for the answer, I am more calm now.
How would you do the code if you consider that I have a my own dataset:
this.abcTableAdapter.Fill(this.dataSet1.abc);

this code:
on form load:
dataAdapter.Fill(dataSet, "Ocene");
dataGridView1.DataSource = dataSet.Tables["Ocene"];
and on button click:
dataGridView1.EndEdit();
dataAdapter.Update(dataSet.Tables["Ocene"]);
dataSet1.Tables["Ocene"].AcceptChanges();

And btw, why there in the code is no where used "ocena" (fromDataGridViewComboBoxColumn) I would say that "ocena" has to be used somewhere in the code below it, because I choose from it the new value. Or am I wrong?

Thank you for your reply.. looking forward to it. Really appreciate your effort.

I am a newbie at C#, so please don`t be mad if I`ll ask some stupid questions :)
Mitja Bonca  Thursday, May 07, 2009 2:40 PM

You can use google to search for other answers

Custom Search

More Threads

• Combobox
• Custom Cursor refuse to work...
• Common practice on capturing the click event on MDI application?
• Create and handle controls in runtime in VB 2008
• custom grid/spread - development - any project out there ?
• Form Size
• Loading VB.NET Code Into A Designer
• Referenced controls dll doesn't display controls in toolbox
• URGENT: load form err w/UserControl, VS 2005, "Could not find type <xxx>..."
• Visual Studio Custom DataGrid etc