i have a small project in c#, in one of my forms i have a datagridview with 3 columns one of the columns is comboboxcolumn that bind with a sql server table id and name, i want to insert the datagridview values into another table in the comboboxcolumn i want to insert the id not a name, anyone can tel me how to do that please? this is my insert code
`
for (int i = 0; i < dgv_student.Rows.Count; i++)
{
sc.add_student(dgv_student.Rows[i].Cells[0].Value.ToString(),
Convert.ToInt32(dgv_student.Rows[i].Cells[1].Value),
dgv_student.Rows[i].Cells[2].Value.ToString());
}
`
the cell[1] the the combobox that display a name not the id.
In your example you have :
Name ID
X X
As your database set. When you are getting this from your database you're probably doing :
myDataGridView.DataSource = GetAllFromMyDatabase(); // Select * from stuff
myDataGridView.DataBind();
Giving you all three columns, and the value. Now, if you want to insert only one column, why not just filter the data you're getting from your database/gridview ?
myComboBox.DataSource = GetOnlyIDFromMyDatabaseOrMyDataGrid(); // Select ID from Stuff
myComboBox.DataBind();
If you're binding your asp.net control with only the data you need, rather than getting everything and then filter, you will have less overhead to think about.
Related
Suppose I have used the following MySQL query:
select * from userinfo;
In the database the following columns are available: username, email, pass, secqu, secan;
Now I want to show only the username, and email columns value into my DataGridView.
Now My Question is: How can I do it? Code like something datagridview.rows[index]. .... something like this is used, but I cannot remember. Can anyone help to do this?
N.B: Please do not reply with the following one:
1. change the query into [select username, email from userinfo;];
2. Change which columns will you want hide or not. As the other columns value are required so I need to use the query.
if you don't want to specify the columns in your query and want to fill datagridview with Select * query then you have another option that you can hide columns from the DataGridView.
string[] strShowColumns = new String[] {"username", "email"};
for (int i=0; i < dgv.Columns.Count; i++)
{
if (!strShowColumns.Contains(dgv.Columns[1].Name))
dgv.Columns[i].Visible = false;
}
I have a table of countries having 10 columns. I have already assigned CityName as DataTextField to my DropDownList and Id as DataValueField. Now on SelectedIndexChanged I have to get values from other columns like CityCode. How I can access it?
ddlCity.DataSource = cboxTeam_DS.Tables["MyTable"];
ddlCity.DataTextField = "CityName";
ddlCity.DataValueField= "Id";
ddlCity.DataBind();
On SelectedIndexChanged method, how do I access the CityCode column values ?
I can suggest you two ways of doing this
You can store one more hidden drop down with your Id and CityCode populated in it. So whenever you select the original drop down select the appropriate value from this hidden dropdown list.
Second way is when you get the ID from the ddlCity.SelectedValue you need to retrieve the table again with the criteria and search in your table taking this value as reference to get the City Code.
I prefer you to go for the first one. you can also access the hidden dropdown in the first case using the javascript.
Well here is my solution which I have developed to solve this problem and it is very effective for me.
The first thing I did, I have changed my database query
from
SELECT * FROM Cities ORDER BY CityName Asc;
to
SELECT *, convert(nvarchar(10),id) + ',' + CityCode as idCode FROM Cities ORDER BY CityName Asc;
It returns me a table containing an extra column named as idCode .
As id is int and CityCode is nvarchar, so I convert the id column and gets an extra column contains values of both columns.
And in my code, I have assigned the idCode column to my ddlCity.DataValueField.
ddlCity.DataSource = cboxTeam_DS.Tables["MyTable"];
ddlCity.DataTextField = "CityName";
ddlCity.DataValueField = "idCode";
ddlCity.DataBind();
After that I use comma splice to to split the string into id and code into an array.
string[] strArray = this.ddlCity.SelectedValue.Split(',');
And then use it where I want to use it by accessing the Indexes.
int myId = strArray[0];
string myCode = strArray[1];
You have not bind the CityCode column to drop down. The data for dropdown is kept in ViewState and that does not know other columns. In desktop we can get the object from ComboBox (dropdown) but in asp.net we can not. This is probably to keep the ViewState as small as possible.
You can choose one of these method to accomplish what you need.
You can get the id and send a database call to retrieve the CityCode in SelectedIndexChanged.
You can make the Value column by combination of two columns like id_CityCode and later extract what you need.
You can get directly from your datasource
int CityId = (int)ddlCity.SelectedValue;
DataTable dt = cboxTeam_DS.Tables["MyTable"];
string CityCode = (from DataRow dr in dt.Rows
where (int)dr["Id"] == CityId
select (string)dr["CityCode"]).FirstOrDefault();
I suggest that with the ID, retrieve again the fields you need on the database. This way you save time and effort. That was how I solved it.
I am using DataGridView with 5 Column AS
SrNo Name Address City Country
Whenever i am retrieving Data From Data Grid View i Use Following Code :
SomeoneName = MYdataGrid[1,1].Value ;
I have one problem with above code that if i add any Column so in entire program i should be re arrange the column no.s for example if I add FirstName Column before name Column then
SomeoneName = MYdataGrid[1,1].Value ;
code will change as
SomeoneName = MYdataGrid[2,1].Value ;
My Question is there is any way to rearrange colomn nos. Automatically...
When you Assassin DataGridView Columns then give column Name Same As your Column Header like
_SrNo _Name _Address _City _Country
and whenever want to use datagridview value use
SomeoneName = MYdataGrid[_Name.Index,1].Value ;
so whenever how many columns you add it will rearrange Automatically.
Hope This Will Help
I am working with C# Window Form, I have created a form connect to mySQL database and it display list of databases, list of tables on each database and also tables contents of each table.
Questions that I have here:
After I selected a random cell in the table (datagridview) and click Delete button, I want that row (corresponding to the selected cell) to be deleted on the database.
I also need that the datagridview table content also will be refreshed and updated (with that row has been removed). (This part I think I can do if I know how to do the part 1)
So I need help with the question 1, one of those things I can't not figure out is that how can I write the SQL statement to put in the SQLadapter or SQLcommandbuilder or whatever it is. I know the SQL statement should be like:
Delete from (selected Table) Where (THIS IS THE PART WHERE I STUCK AT) => I dont know what to put in this condition, how to get it?
Any helps and advises is really appreciated!
The delete statement should consider all the selected table primary key columns and the selected row from the datagridview.
How to get the primary key columns:
SELECT `COLUMN_NAME`
FROM `information_schema`.`COLUMNS`
WHERE (`TABLE_SCHEMA` = 'dbName')
AND (`TABLE_NAME` = 'tableName')
AND (`COLUMN_KEY` = 'PRI');
Source: A better way to get Primary Key columns
How your delete statement should look like:
DELETE FROM <TABLE>
WHERE <PRIMARY_KEY_COLUMN_1> = <ROW_VALUE_1>
AND <PRIMARY_KEY_COLUMN_2> = <ROW_VALUE_2>
You see, the table could have multiple columns uniquely identifying a row. There is also the possibility of existing a reference for that very row on another table, which would prevent you from deleting it.
It would look like this:
List<string> primaryKeyColumns = GetPrimaryKeyColumns(SelectedDB, SelectedTable);
string deleteWhereClause = string.Empty;
foreach (string column in primaryKeyColumns)
{
DataGridViewRow row = datagridview.CurrentCell.OwningRow;
string value = row.Cells[column].Value.ToString();
if (string.IsNullOrEmpty(deleteWhereClause))
{
deleteWhereClause = string.Concat(column, "=", value);
}
else
{
deleteWhereClause += string.Concat(" AND ", column, "=", value);
}
}
string deleteStatement = string.Format("DELETE FROM {0} WHERE {1}", SelectedTable, deleteWhereClause);
The method GetPrimaryKeyColumns returns the names of all the primary key columns of the selected table using the select statement i posted.
You would also have to deal with other types of columns such as dates and strings, but that's basically what you will have.
Friends, I'm using datagridviewcomboboxcolumn as column index 1 in my datagridview. I've fetched data from access database table and populated the datagridviewcomboboxcolumn by following manner:
for (int i = 0; reader.Read(); i++)
{
cmbBusCode.Items.Add(reader["BUSINESS_CODE"] + "-" + reader["BUSINESS_DESCRIPTION"]);
cmbBusCode.ValueMember = "BUSINESS_CODE";
}
Then I'm writing this:
cmbBusCode.DisplayIndex = 1;
cmbBusCode.Width = 200;
cmbBusCode.Name = "Code";
cmbBusCode.HeaderText = "Code";
And adding this column as
dgView.Columns.Add(cmbBusCode);
Combobox is being populated and I can select any one from the list. Now when I'm saving data I want to get the ValueMember of the selected item. To get this value I'm using following code but It's giving the string representation of the field "BUSINESS_CODE" not the value..Please help me so that get ValueMemeber of the selected item..
foreach (DataGridViewRow row in dgView.Rows)
{
string cd = row.Cells["Code"].Value.ToString();
}
The "item" you are adding to the column doesn't have a "BUSINESS_CODE" column (essentially, the item as you add it is simply a string), so that doesn't work.
What you need to do is assign items that contain multiple columns. One must be the BUSINESS_CODE column (as it is this column you want to be the value for the underlying field in the DataGridView), the other should be a display column that contains the concatenated value you're adding at the moment (DisplayMember and ValueMember).
Easiest would be to create a typed data set, add a table that contains the two columns I described and fill the table with the data from the data reader.
Then, add the table as the data source for the column.
You can try adding a DataGridViewComboBoxCell instead of a string to the cmbBusCode.Items collection. You can then specify Value in the cell. I'm not sure if this will work, but it's worth a try.