Inserting data to GridView using CheckBox - c#

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();

Related

How to Disable a button in dataGridView which is not clickable(c# windows application)

I found many similar questions and answers but none help me to solve my issue.
Here is a screenshot of my application where i'm facing this problem
dataGridView with buttoncell
I want to disable(or not clickable) the button if the button text says "ACCEPTED",
here is what i have and that is not working
private void Cellcontent()
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if ((row.Cells["Status"].Value.ToString()) == "ACCEPTED")
{
DataGridViewButtonCell cell = row.Cells["Status"] as DataGridViewButtonCell;
cell.ReadOnly = true; //if 1 cell will be disabled (not clickable)
}
}
}
I have created a small demo
https://github.com/manojsethi/DataGridViewDisableButton
Information gathered from MSDN
Hope it helps
you could do the following if you dont mind using a a different cell when the value is not ACCEPTED:
foreach (DataGridViewRow item in dataGridView1.Rows.OfType<DataGridViewRow>().Where(c => c.Cells[buttonCol.Index].Value != null && c.Cells[buttonCol.Index].Value.ToString() == "ACCEPTED"))
{
//you can replace the button with a textbox cell that contains the rejected value
item.Cells[buttonCol.Index] = new DataGridViewTextBoxCell { Value = "ACCEPTED" };
item.Cells[buttonCol.Index].ReadOnly = true;
//note that you have to make a new button cell and replace the rejected ones if the status is updated later on to be able to use the button.
}
hope this helps.

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.

C# Datagridview - Check Row is Selected

I have this code in my C# program, but it throws a fit when some buttons are clicked because there is no row selected in the DataGridView (I use the ClearSelection method):
string selectedUser = usersGrid.SelectedRows[0].Cells[1].Value.ToString();
Is there some sort of check I can do before the above line to ensure that a row is selected?
if (usersGrid.SelectedRows.Count > 0)
I am going to take a stab at what I think you are trying to do, try this below
private void myButton_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in usersGrid.Rows)
{
if (this.usersGrid.SelectedRows.Count == 1)
{
// get information of 1st column from the row
string selectedUser = this.usersGrid.SelectedRows[0].Cells[0].ToString();
}
}
}
also do the following as well and checkout the link
Set DataGridView.MultiSelect=false and DataGridView.SelectionMode = FullRowSelect. This will make it so the user can only select a single row at a time.

Question about checkbox and datagridview

I have datagridview with checkbox column, and the checkbox within the column can be checked or unchecked with external checkbox. It works fine while selecting all the columns and saving the data in database. But, when I unchecked the checkbox in the datagridview with external checkbox and again select the single checkbox within the datagridview, it again takes the rowindex of all the checkbox within the column.
if (chkbranches.Checked == true)
{
foreach (DataGridViewRow dr in gridviewholiday.Rows)
{
dr.Cells[0].Value = true;
}
for (int i = 0; i < gridviewholiday.Rows.Count; i++)
{
rowindex = i;
list.add(rowindex);//to put the rowindex in array list
}
}
else if (chkbranches.Checked == false)
{
foreach (DataGridViewRow dr in gridviewholiday.Rows)
{
dr.Cells[0].Value = false;
gridviewholiday.Refresh();
gridviewholiday.ClearSelection();
list.Clear();
}
}
Why do you loop twice if chkbranches is checked? Can't you add items to the list within the first foreach? And in the loop for unchecking, why do you refresh, and clear both controls each time? Probably only needed once.
And as mentioned, this isn't doing anything about single checks. If you're expecting it to, that seems to be the problem.
Not quite sure what your attempting to do, but I have something similar with a button that deletes all the checked rows. I use a template field like so for the check box:
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="cbSelector" runat="server" />
</ItemTemplate>
</asp:TemplateField>
Then for the Delete button code behind I do:
protected void btnDeleteChecked_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in gridOrders.Rows)
{
CheckBox cb = (CheckBox)row.FindControl("cbSelector");
if ((null != cb) && cb.Checked)
{
uint id = Convert.ToUInt32(gridOrders.DataKeys[row.RowIndex].Value);
gInvoiceDB.DeleteInvoice(id, true);
}
}
}

How to check for an Empty Gridview

I have an ASP.NET 2.0 (C#) web app, and in it I have a gridview that gets its data from an oracle database.
I want to know how to check if the gridview is empty, and the do something.
I have already tried:
if(GridView.Rows.Count == 0)
{
// Do Something
}
but it doesn't work...
Any ideas?
Thank you.
Your code should work. But only after GridView.DataBind() has been called. Generally I don't check the GridView it's self, but the datasource of the grid view.
DataTable data = DAL.getdata();
if (data.Rows.Count == 0)
{
ShowEmptyData();
}
else
{
Grid.DataSource = dt;
Grid.DataBind();
}
This doesn't work since the GridView is data bound and is going to fetch the actual data at a later time while rendering the page. You should check this by directly querying the data binding source of the gridview (see if the actual list that's grid view bound to is empty or not).
If you just want to display something when it's empty, you should use <EmptyDataTemplate> in your markup:
<asp:GridView runat="server">
<EmptyDataTemplate>The grid is empty</EmptyDataTemplate>
</asp:GridView>
I agree with the other responses. I want to add little information, you should get rows.count after databind method :
int rowCount = GridView.Rows.Count; // returns zero
GridView.DataBind();
rowCount = GridView.Rows.Count; // returns actual row count
If you're using databinding, the the row count of the datasource not the count on the grid itself.
Its very easy: Hope it works for you.. :)
Use event of GridView DataBound: which fires after data is bound.
protected void GridView1_DataBound(object sender, EventArgs e)
{
int rowCount = GridView1.Rows.Count;
if (rowCount == 0)
{
GridView1.Visible = false;
}
else
{
GridView1.Visible = true;
}
}
First create a helper class.
public static class GridViewExtensions
{
public static IEnumerable<GridViewRow> AsEnumerable(this GridView grid)
{
foreach (GridViewRow row in grid.Rows)
{
yield return row;
}
}
public static bool IsEmpty(this GridView grid)
{
return !grid.AsEnumerable().Any(t => t.RowType == DataControlRowType.DataRow);
}
}
Then just call IsEmpty
GridView1.IsEmpty()
In case you've configured your GV to automatically fetch the data from DB, then you may add the following line as the first statement of your GV in Source mode:
<EmptyDataTemplate>No data found.</EmptyDataTemplate>
And then continue with the normal code in your GV.
Based on answers already, GridView.Rows.Count is not enough on its own, depending on the nature of your GridView, especially if it's a dynamic gv, which in most cases it is, plus you have to factor in Paginating, Headers and Footers, which alter the row count.
I use a simple method to tell me ...
//checks if a gridview has any actual rows of data (not just blank rows filled in by the Load
protected bool gvNoData(GridView gv)
{
int wsDataRow = 0;
foreach (GridViewRow gvRow in gv.Rows)
if (gvRow.RowType == DataControlRowType.DataRow)
{
HiddenField hf = (HiddenField)gvRow.FindControl("hfStudentID");
if (hf != null)
if (hf.Value.ToString().Length > 0)
wsDataRow +=1;
}
//if a count was generated then there are data rows, otherwise the rows are blank or nonexistant
if (wsDataRow > 0) return false;
else return true;
}
So running something like this will tell you if the Rows are really "
"DATA" rows, or empty or nothing!
Obviously in my case I have a HiddenField to tell me if the GridViewRow is an actual data row, as I prefill my gridview with blank rows (for my purposes) and some datarows.
However, a simpler version to check based on DataRow vs HeaderRow, etc...
foreach (GridViewRow gvRow in myGridView.Rows)
if (gvRow.RowType == DataControlRowType.DataRow)
{
//do what you need
}
I hope this helps.
In short, there is no GridView.IsEmpty() function unfortunately, unless you enumerate one as shown below.

Categories