I want to create a form which I can open tables within different database and delete some lines.
looks like this. the tables are different. so I use
boxGrid.Controls.Clear();
DataGridView g = GetTableGrid(databaseName);
boxGrid.Controls.Add(g);
GetTableGrid() will generate a new DataGridView and replace the one before
it works will on changing table. but causes problems for me to get the selected row in the table to delete.
What can I do?
I only need to get the first col in the row. It is the primary key in the database.
the problem here is that you are always creating a new datagridview whenever the user selects a new table (i would assume its the buttons below the datagridview)
What you can do is before adding the datagridview on your boxgrid object, you can add an SelectionChanged to it.
boxGrid.Controls.Clear();
DataGridView g = GetTableGrid(databaseName);
g.SelectionChanged += new EventHandler(dvg_SelectionChanged);
boxGrid.Controls.Add(g);
and then you can get the value you are looking for like this
private void dvg_SelectionChanged(object sender, EventArgs e)
{
DataGridView dvg = (DataGridView)sender;
//Check first if datagridview has data and
//Check if you are selecting a valid row
if (dvg.Rows.Count > 0 && dvg.CurrentCell.RowIndex > 0)
{
int index = dvg.CurrentCell.RowIndex;
DataGridViewRow row= dvg.Rows[index];
string mykey = Convert.ToString(row.Cells["columnName"].Value);
//Or you can store the information you've got here to some
//Variable you can use to open the form you want.
}
}
If you're only trying to get a certain column (in this case, the first one) of a clicked row you can do the following (it's how I do it):
private void yourGridView_SelectionChanged(object sender, EventArgs e)
{
//makes sure a row is selected
if (yourGridView.SelectedCells.Count > 0)
{
int selectedrowindex = yourGridView.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = yourGridView.Rows[selectedrowindex];
//guessing you´re storing your value in a variable
string a = Convert.ToString(selectedRow.Cells["columnName"].Value);
//where columnName is the name of the column you want the value printed of...
}
}
Related
In my form I have datagrid view and I select the data into datagridview by using the following
stored procedure :
create proc [dbo].[GET_CULTURE_RESULT_DETAILS]
#ORDER_ID int
as
select LAB_MICRO_RESULTS_DETAILS.[organism_id] as 'Org.Id' , organism_desc as 'Organism Name'
,LAB_MICRO_RESULTS_DETAILS.[Antibiotic_id] as 'Ant.Id', Antibiotic_Name as 'Antibiotic Name'
,LAB_MICRO_RESULTS_DETAILS.[sensitivityId] as 'Sens.Id', Sensitivity_desc as 'Sensitivity Name'
from LAB_MICRO_RESULTS_DETAILS
inner join lab_organisms on LAB_MICRO_RESULTS_DETAILS.organism_id = lab_organisms.organism_id
inner join lab_antibiotics on LAB_MICRO_RESULTS_DETAILS.Antibiotic_id = lab_antibiotics.Antibiotic_id
inner join Lab_Sensitivity on LAB_MICRO_RESULTS_DETAILS.sensitivityId = Lab_Sensitivity.sensitivityId
where LAB_MICRO_RESULTS_DETAILS.order_id = #ORDER_ID
Then when select the order number datagridview filled using key down event this is the code :
private void txtOrder_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter && txtOrder.Text != string.Empty)
{
dgvcultures.DataSource = micro.GET_CULTURE_RESULT_DETAILS(Convert.ToInt32(txtOrder.Text));
txtPCfile.Focus();
}
}
Finally the error appeared when I try to add new row into the datagrid view by using this code :
private void btnAdd_Click(object sender, EventArgs e)
{
if (dgvcultures.Columns.Count >= 0)
{
dgvcultures.ColumnCount = 6;
dgvcultures.Columns[0].Name = "Org.Id";
dgvcultures.Columns[1].Name = "Organism Name";
dgvcultures.Columns[2].Name = "Ant.Id";
dgvcultures.Columns[3].Name = "Antibiotic Name";
dgvcultures.Columns[4].Name = "Sens.Id";
dgvcultures.Columns[5].Name = "Sensitivity Name";
dgvcultures.Rows.Add(comboOrganism.SelectedValue.ToString(), comboOrganism.Text,
comboAntibiotics.SelectedValue.ToString(), comboAntibiotics.Text,
comboSensitivity.SelectedValue.ToString(), comboSensitivity.Text);
// comboGrowth.SelectedValue.ToString(),comboGrowth.Text);
}
}
when click add button and try to insert new row I got this error :
ColumnCount property cannot be set on a data-bound DataGridView control. c#
I checked the solutions in this site and they said you have to clear the datagridview before insert new rows I tried it its clear the filled data from stored procedure and I dont need to clear datagridview , I need to keep the data and add new rows without clear the current data :
//Clear the binding.
dgvcultures.DataSource = null;
this command will remove the rows in datagridview , but I need to keep rows.
How to solve this error please.
From what I can decipher, the grids DataSource looks like a DataTable with the following columns…
Org.Id, Organism Name, Ant.Id, Antibiotic Name, Sens.Id and Sensitivity Name.
I assume this from the first snippet of code that gets the table from the DB.
If this DataTable is used as a DataSource to the grid, then in the button click event, it is unnecessary to “re-create” the columns. Those columns already exist in the table. The code simply needs to add the row to the DataTable. It is not clear if the column “types” are all strings and the code may have to convert some values, otherwise the code in the button click event may look something like…
DataTable gridDT = (DataTable)dgvcultures.DataSource;
gridDT.Rows.Add(comboOrganism.SelectedValue.ToString(),
comboOrganism.Text,
comboAntibiotics.SelectedValue.ToString(),
comboAntibiotics.Text,
comboSensitivity.SelectedValue.ToString(),
comboSensitivity.Text);
Lastly, you should consider using a BindingSource. It may make things easier.
I hope this makes sense.
I am having below code that successfully adds a check box column to the ultrawingrid, my problem is that when I make a selection by checking a check box on the Select column the count of selected rows of ultrawingrid is not updated and it still shows the count as zero, and also I want to know how to enable multi checkbox selection i.e multiple rows selected...
Below is the code...
private void grdPayVis_InitializeLayout(object sender,InitializeLayoutEventArgs e)
var gridBand = grdPayVis.DisplayLayout.Bands[0];
if(!gridBand.Columns.Exists("Select"))
gridBand.Columns.Add("Select", "Select");
gridBand.Columns["Select"].Header.VisiblePosition = 0;
gridBand.Columns["Select"].Hidden = false;
gridBand.Columns["Select"].Style = Infragistics.Win.UltraWinGrid.ColumnStyle.CheckBox;
gridBand.Columns["Select"].AutoSizeMode = ColumnAutoSizeMode.AllRowsInBand;
gridBand.Columns["Select"].CellClickAction = CellClickAction.Edit;
}
I am not sure what you actually is trying to achieve. When you set CellClickAction in your Select column to Edit, and you click on any cell in this column the grid will select the cell and not the row. Grid has Selected property which exposes three collections - rows, columns and cells. In your case you are changing the selected cells and do not change the selected rows collection. If you need to select rows you need to set CellClickAction in your Select column to RowSelect. If you need in the same time to shange the checkbox state of the Select column you may handle AfterSelectChange event of the grid like this:
private void grdPayVis_AfterSelectChange(object sender, AfterSelectChangeEventArgs e)
{
if (e.Type == typeof(UltraGridRow))
{
foreach (UltraGridRow row in this.grdPayVis.Selected.Rows)
{
row.Cells["Select"].Value = true; // Or some value appropriate to your scenario
}
this.grdPayVis.UpdateData();
}
By default, the grid allows you to select many cells, rows or columns. However, when there is a cell in edit mode you cannot select any other cells. So again, as you have set CellClickAction to Edit when you click any cell in Select column it enters edit mode and no more cells could be selected before you exit edit mode.
You can add a new column to your datatable AFTER reading it from the database
ds = new DataSet("PayCharge");
ds= obj.GetData();
DataColumn dc = new DataColumn("Select", typeof(boolean));
dc.DefaultValue = false;
ds.Tables[0].Columns.Add(dc);
grdVisPay.SetDataBinding(ds, "PayCharge");
.....
Now the first table in your dataset has an unbound column named Select and when you set that as your datasource you will be able to manipulate as you have already done. But this time whenever you touch the checkbox the value True/False will be set in the underlying datatable. When you need to discover what are the checked rows you work with the datasource, not with the grid. For example
void buttonSave_Click(object sender, EventArgs e)
{
DataSet ds = grdVisPay.DataSource as DataSet;
DataRows[] selectedRows = ds.Tables[0].Select("Select = True");
foreach(DataRow row in selectedRows)
{
... do whatever you need with the selected row...
}
}
I am using the following code to update the database.
int lastRow = inventoryDataGridView.Rows.Count - 1;
inventoryDataGridView.Rows[lastRow].Cells[1].Value = variableName;
However, if multiple rows are added before the database is saved then it will only save the last one. So then I tried this code.
foreach (DataGridViewRow row in this.inventoryDataGridView.Rows)
{
row.Cells[1].Value = variableName;
}
The problem with this is that it will update every cell in the given column to include the cells that already have a value. This is not efficient. Any suggestions on how to update just the given column of the newly added rows?
Thank You.
This seems to serve my purpose. As soon as I start typing in the blank row it will add another row to the datagridview and populate the given column of the new row I am entering with the variableName value.
private void inventoryDataGridView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
int lastRow = inventoryDataGridView.Rows.Count - 1;
inventoryDataGridView.Rows[lastRow - 1].Cells[2].Value = accountNumber;
}
I have a GridView with data. The first column on this GridView is the "SELECT" column.
If the user clicks on SELECT, it highlights the entire row.
I have an event on this click action:
protected void gvShows_SelectedIndexChanged(object sender, EventArgs e)
{
}
Basically what I want to do is for each SELECTED row, I want to extract the values for the columns:
dataSource
showId
episodeId
**Here's where I'm having problems:
string dataSource = "";
int showId = 0;
int episodeId = 0;
foreach (DataRow row in gvShows.Rows)
if (the row is selected/highlighted then...)
{
dataSource = the value under column "dataSrouce" for this ROW.
showId = the value under column "showId" for this ROW.
episodeId = the value under column "episodeId" for this ROW.
}
Can anyone give me a hand with this?
I believe you will want to use SelectedIndexChanging (and not SelectedIndexChanged) because that will give you access to the new selected row index. If the first cell is the button, the next three should give you the values you need:
protected void gvShows_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
GridViewRow r = gvShows.Rows[e.NewSelectedIndex];
string dataSource = r.Cells[1].Text;
int showId = Convert.ToInt32(r.Cells[2].Text);
int episodeId = Convert.ToInt32(r.Cells[3].Text);
}
Edit:
I wanted to add that you can use the SelectedIndexChanged if you didn't want to use SelectedIndexChanging:
protected void gvShows_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow r = gvShows.Rows[gvShows.SelectedIndex];
string dataSource = r.Cells[1].Text;
int showId = Convert.ToInt32(r.Cells[2].Text);
int episodeId = Convert.ToInt32(r.Cells[3].Text);
}
And if you are working with a database, you can add a datakey to the gridview, allowing you to pull the primary key for the record you want to work on.
Add the following to your gridview:
DataKeyNames="showId"
And then you can access this value from the codebehind:
int showId = Convert.ToInt32(gvShows.DataKeys[gvShows.SelectedIndex].Value);
You need to rely on the "selected/highlighted" rows' attributes. Find any attribute that could determine if it is a selected row.
EventArgs e should have a Row property that represents the selected row. Within there, you have access to each of the columns (called Cells). You get into each particular cell using indexing. So, if ShowId is in column 3, here's how you'd access it:
e.Row.Cells[2]; (remember, it's 0-based indexing in C#).
First to get ShowId, try e.Row.Cells[2].Text; That might get you what you need.
If that doesn't work, try this:
Now, within Cells[2], you have access to Controls, which again is a list of controls in that cell. Run your code, and put a breakpoint inside of SelectedIndexChanged. Then in your immediate window, type the code above, and hover your mouse over Cells[2] to open up the items in there. Hover again on Controls, and look at what's in there.
Usually there's a LiteralControl, then your control with ShowId, then another LiteralControl.
Validate that, and then you'll be able to access it like e.Row.Cells[2].Controls[1].Text or something like that.
Alright so I have two columns one called "id", other one called "note".
My plan to make it so that when users doubleclick the ID something happens (a website containing that ID opens in a webbrowser control).
However if the user would doubleclick on the note, it obviously couldn't open the site with the ID, so what I want to do it when the user doubleclicks on a note that it selects the 'id' value in that row and uses that to open the webbrowser.
Anyone have any clue how to do this?
tl;dr: I want to select cell with name 'id' in the selected row
Use the CellClick or DoubleClick event.
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
int row = e.RowIndex;
int column = e.ColumnIndex;
//using DataGridview or DataSource with the row or column indexes to get the ID
}
I found a solution, I made it select the entire row instead (which is more clean anyway)
and and then this code will select the first selected cell (meaning the first cell of the row)
public void SelectIdCell()
{
favorite_GridView.ClearSelection();
foreach (DataGridViewCell cell in favorite_GridView.CurrentRow.Cells)
{
if (cell.Visible)
{
cell.Selected = true;
return;
}
}
}