How to Get cell index in gridview - c#

I'm using a website(asp.net,C#) to view some details in gridview. In that gridview I have generated checkboxes dynamically. So it will be placed any cell inside of that gridview. I find that control in grdview by using FindControl(), but I cant get that cell index... now I want to get that excact cell index which placed that checkbox. How shall I get that cell index?
Please anyone Tell me the solution of this problem.
Thanks in advance.
My code for getting that Control is:
if (HeaderCell.Text.Contains(strColumnName))
{
CheckBox chk = GrdDynamicControls.Rows[index].FindControl(chkCheckBox1.ID) as CheckBox;
chk.Checked = true;
strCelValue = chk.Checked.ToString();
}

Try this:
int theCellNumberWhatINeed = -1;
for (int cellNumber = 0; cellNumber < GridView1.Rows[index].Cells.Count; cellNumber++)
{
foreach (Control ctrl in GridView1.Rows[index].Cells[cellNumber].Controls)
{
if (ctrl.ID == "aCheckBox") // or compare by clientid... etc
{
theCellNumberWhatINeed = cellNumber;
break;
}
}
}
if (theCellNumberWhatINeed > -1)
{
// ...
}
Not the most elegant solution but works with the builtin gridview control without creating your own.

You can use Event Args e
e.Item.ItemIndex
it will return an integer
Hope this will help

Related

DataGrid Select Cells in only one Row

Is there a way to let the user only select one row in a datagrid
For example that should the user can do:
That he should can't do:
i saw this but it dont see how to use that for my problem:
https://stackoverflow.com/a/3072929/1764978
I wanted to use the SelectionChanged on the DataGrid, but it doesnt trigger when i change selected cells, just only SelectedCellsChanged and there is no Handled-Property
Edit
When im using ethicallogics solution i got:
I select a full row.. thats not what i want
This might be optimized, but this worked for me.
It keeps track of the first selected item, meaning the row, and if there is a selection outside of that row, it removes the whole selection (and replaces it with the newly selected cell). It could be enhanced, probably, to restore the initial selection, but my usecase didn't need that.
Anyway, see if this works for you.
private object selectedItem;
private void DataGrid_OnSelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
var dg = (sender as DataGrid);
if (selectedItem == null)
selectedItem = e.AddedCells.First().Item;
var allInSameRow = e.AddedCells.All(info => info.Item == selectedItem);
if (!allInSameRow)
{
dg.SelectedCells.Clear();
selectedItem = null;
}
}
If my guess is correct : you want is
1) Allow the user to select one cell from the whole grid.
2) After first selection you want the user not to select any cells from any other row.
3) If user wants to select multiple cells then he is allowed to do so but in the same row in which he has selected the first cell.
I don't know the exact solution or I don't have any code to guide you.
But If you can then disable other rows at the time of first selection.
int _selectedRow = -1;
int _selectedColumn = -1;
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
switch (dataGridView1.SelectedCells.Count)
{
case 0:
// store no current selection
_selectedRow = -1;
_selectedColumn = -1;
return;
case 1:
// store starting point for multi-select
_selectedRow = dataGridView1.SelectedCells[0].RowIndex;
_selectedColumn = dataGridView1.SelectedCells[0].ColumnIndex;
return;
}
foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
{
if (cell.RowIndex == _selectedRow)
{
if (cell.ColumnIndex != _selectedColumn)
{
_selectedColumn = -1;
}
}
else if (cell.ColumnIndex == _selectedColumn)
{
if (cell.RowIndex != _selectedRow)
{
_selectedRow = -1;
}
}
// otherwise the cell selection is illegal - de-select
else cell.Selected = false;
}
}
Try this
<DataGrid SelectionMode="Single" SelectionUnit="Cell"
I am currently working on something like that and I am creating string variables for every record that I want to take. I use this line of code:
string somename = ((DataRowView)DataGridName.SelectedItem).Row["ColumnName"].ToString();
this code will take only one cell (it depends of the ColumnName which record will be stored in the variable) from the row the user selected.

Inserting data to GridView using CheckBox

I have a GridView and I put checkboxes inside all its cells. I want to do the following:
if the checkbox checked by the user, this means Yes which will be stored in the database
else, if the checkbox unchecked by the user, this means No and no need to post anything to the database.
I know I need now to identify each checked checkbox and know which cell this checked checkbox is underneath it.
Any idea about how to do that? Could anyone give me the basic piece of code for doing this?
I use something similar to this:
foreach (GridViewRow row in gvYourGridView.Rows)
{
CheckBox ck = ((CheckBox)row.FindControl("YourCheckBoxName"));
if (ck.Checked)
{
//If checked is true, update database.
}
}
int counter = 0;
foreach (GridViewRow rowitem in gvYourGridView.Rows)
{
if (((CheckBox)rowitem.Cells[0].FindControl("chk")).Checked == true)//i consider that the check box is in the first column index ---> 0
{
counter++;
}
}
/////////////////////////////////////////////////////////////
if(counter == 0) //no checks
{
//show some message box to clarify that no row has been selected.
}
/////////////////////////////////////////////////////////////
if (counter == 1) //one check
{
//Do something
}
/////////////////////////////////////////////////////////////
if (counter > 1) //more than one check
{
//Do something
}
gvYourGridView.DataBind();

Is there a way to use OnMouseOver to select a radgrid row?

I am currently highlighting a row in a radgrid using OnMouseOver. I would like to know if it is possible to use OnMouseOver to select the row rather than highlight it.
Alternatively, I would like the highlighted row to remain highlighted if the radgrid loses focus, such as when a confirmation box pops up.
Thanks in advance.
According to Telerik documentation, it should be possible to select the item OnMouseOver using the following code (if you don't have any detail tables you can nix the if statement and just use the code from the else block to find the currentDataItem):
function RadGrid1_RowMouseOver(sender, eventArgs) {
var currentDataItem = null;
// clear all currently selected items before selecting new
sender.get_masterTableView().clearSelectedItems();
if (eventArgs.get_itemIndexHierarchical().indexOf(':') > 0)
{
var detailTableIndex = eventArgs.get_itemIndexHierarchical().split(':')[0];
var rowIndex = eventArgs.get_itemIndexHierarchical().split(':')[1].split('_')[1];
currentDataItem = sender.get_detailTables()[detailTableIndex].get_dataItems()[rowIndex];
}
else
{
currentDataItem = sender.get_masterTableView().get_dataItems()[eventArgs.get_itemIndexHierarchical()];
}
if (currentDataItem != null)
{
currentDataItem.set_selected(true);
}
}
The other answers here do not work with the WPF Telerik RadGridView as we don't have access to RowMouseOver event.
For a WPF Telerik RadGridView, the best approach if the grid doesn't contain UI elements is to use ChildrenOfType<> in a Linq expression with IsMouseOver.
private void myGridView_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
{
MyCustomClass myClass = null;
var rows = this.myGridView.ChildrenOfType<GridViewRow>().Where(r => r.IsMouseOver == true);
foreach (var row in rows)
{
if (row is GridViewNewRow) break;
GridViewRow gvr = (GridViewRow)row;
myClass = (MyCustomClass)gvr.Item;
}
// do something with myClass here if we have found a row under mouse
}
Thanks! Your solution worked great, but rows would not become unselected when mousing over another row even if AllowMultiRowSelection was set to False. The following code will select a single row in the radgrid when the mouse hovers over the row:
<script type="text/javascript">
function grdUsers_RowMouseOver(sender, eventArgs) {
var NumberItems = sender.get_masterTableView().get_dataItems().length;
for (var count = 0; count < NumberItems; count++) {
var currentDataItem = sender.get_masterTableView().get_dataItems()[count];
if (count == eventArgs.get_itemIndexHierarchical()) {
currentDataItem.set_selected(true);
}
else {
currentDataItem.set_selected(false);
}
}
}
</script>
I called the function at the following location:
<ClientSettings AllowColumnsReorder="True" ReorderColumnsOnClient="True">
<Selecting AllowRowSelect="True" />
<ClientEvents OnRowMouseOver="grdUsers_RowMouseOver" />
</ClientSettings>

Checkbox in gridview

As I have check box in gridview if i dont select any one checkbox and if i click asp button then i have to show message to user to select checkbox
awaiting response
Should be something like you need...
Boolean Selected = false;
for (int count = 0; count < grd.Rows.Count; count++)
{
if (((CheckBox)grd.Rows[count].FindControl("yourCheckbox")).Checked)
{
Selected = true;
}
}
if (Selected == false)
{
//your message goes here.
}
if you need javascript code...
function CheckIfSelect() {
var frm = document.forms[0];
var Selected=false;
for (i = 0; i < frm.elements.length; i++) {
if (frm.elements[i].type == "checkbox") {
if(frm.elements[i].checked)
{
Selected=true;
break;
}
}
if(Selected==false)
{
//your message goes here
}
}
}
If you want to do this client side you could use a library like jQuery to iterate through the checkboxes.
If you want to do this server side, you will need to reenumerate the controls on postback, and check the Checked value. Alternatively if this GridView binds to a DataSource, check the posted back values within the DataSource.

C# dynamically taking data from DataGridView

I'm trying to get my current program to take information from a dynamically created DataGridView. I have managed to get the information into the grid, and perform the required search, however now I'm really stuck.
I have added a column to the datagridview which holds a button within each row. What I'd like to do is take the value of the data from column index 1 which is in the same row as the button clicked. Confusing? Anyway, here's the code:
public void GetValues(...)
{
//Details regarding connection, querying and inserting table
.
.
.
DataGridViewButtonColumn buttonCol = new DataGridViewButtonColumn();
buttonCol.Name = "ButtonColumn";
buttonCol.HeaderText = "Select";
buttonCol.Text = "Edit";
//NB: the text won't show up on the button. Any help there either?
dataGridView1.Columns.Add(buttonCol);
dataGridView1.CellClick += new DataGridViewCellEventHandler(dataGridView1_CellClick);
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataGridViewButtonCell button = (row.Cells["ButtonColumn"] as DataGridViewButtonCell);
}
dataGridView1.Columns["ButtonColumn"].DisplayIndex = 0;
}
void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
//Here is where I'm having the trouble. What do I put in here???
}
Thanks for any help you can give!
David.
Your DataGridViewCellEventArgs contains very useful information such as RowIndex.
So something like (I don't know what you want to do with the value):
String dataYouWant = dataGridView1.Rows[e.RowIndex].Cells[1].Value;
`
if (e.ColumnIndex != button_column_number) //column number of the button.
return;
dataGridView1.EndEdit();
bool val;
if ((dataGridView1.Rows[e.RowIndex].Cells[1].Value) != null) // column index 1...as that's what you want.
{
//d stuff you want here.
}
else
{
}
`

Categories