How to convert cells of DataGridView to int? - c#

I tried
int A = DataGridView1.Rows[0].Cells[3].value
and
int A = (int)DataGridView1.Rows[0].Cells[3].value
or using Cast or Parse method but it doesn't work.

You shouldn't be doing any of these things.
Your DataGridView should be databound (databind'd) to a DataTable that has a fourth column that is an integer or to a list of objects that has a property that appears in the fourth column of the datagridview, that is an integer:
var x = (int)myDataTableThatTheDGVIsBoundTo.Rows[0][3];
var x = myListOfPeopleWhereAgeAppearsAsDGVFourthColumn[0].Age;
DataGridView is intended for VIEWing a model of data that is kept elsewhere. If you want data out of the model, you get it from the model, not the view. If you want to know something that is eg what the user selected in the view, or is the current row etc you either retrieve the relevant model rows from the SelectedCell's OwningRow.DataBoundItem or use something like a bindingsource that understand sthe concept of "current row"
To really answer this we need a lot more info about how your data got into your grid in the first place. I get the feeling it's not in a model at all :/

try
{
string cellValue = DataGridView1.Rows[0].Cells[3].Value.ToString();
int intCellValue = System.Convert.ToInt32(cellValue);
}
catch (FormatException e)
{
Console.WriteLine(e.Message);
}
The try-catch block is used in case the user somehow inserted a non-integer value in the datagrid.

Something like that will work too.
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
e.Control.KeyPress -= new KeyPressEventHandler(Column1_KeyPress);
if (dataGridView1.CurrentCell.ColumnIndex == 0) //Desired Column
{
TextBox tb = e.Control as TextBox;
if (tb != null)
{
tb.KeyPress += new KeyPressEventHandler(Column1_KeyPress);
}
}
}
private void Column1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
Found this code sample on another thread.

dgwProducts.Rows[0].Cells[3].Value
return object.
You can this:
int A = Convert.ToInt32(dgwProducts.Rows[0].Cells[3].Value.ToString());

Related

How to change RepositoryItem without using CustomRowCellEdit?

I would like to change RepositoryItem in diffrent way than shown in the code bellow. Motivation to do this is described in obsolete field CustomRowCellEditEventArgs.RowHandle.
private void GridView_CustomRowCellEdit(object sender, CustomRowCellEditEventArgs e)
{
GridView view = sender as GridView;
if (e.Column.FieldName == CONSTS_FIELD_NAME)
{
var val = (VAL_TYPE) view.GetRowCellValue(e.RowHandle, CONSTS_FIELD_NAME);
if (val == VAL_VALUE)
e.RepositoryItem = new RepositoryItem(); // setting new Repository Item
}
}
So I decided to use this code:
private void GridView_CustomRowCellEdit(object sender, CustomRowCellEditEventArgs e)
{
GridView view = sender as GridView;
if (e.Column.FieldName == CONSTS_FIELD_NAME)
{
var result = view.GetSelectedRows();
var val = (VAL_TYPE) view.GetRowCellValue(result.First(), CONSTS_FIELD_NAME);
if (val == VAL_VALUE)
e.RepositoryItem = new RepositoryItem(); // setting new Repository Item
}
}
Is there any other way to change RepositoryItem using some events?
The situation with CustomColumnDataEventArgs you mentioned(providing unbound data for the specific column) have no relation with GridView's editing process. When the CustomRowCellEdit event is fired all the row handles are already calculated. Thus there is no motivation to avoid the first approach.
The only recommendation I can suggest is to use the predefined repository item instead of creating a new one every time:
void GridView_CustomRowCellEdit(object sender, CustomRowCellEditEventArgs e) {
GridView view = sender as GridView;
if(e.Column.FieldName == CONSTS_FIELD_NAME) {
var val = (VAL_TYPE)view.GetRowCellValue(e.RowHandle, CONSTS_VAL);
if(val == VAL_VALUE)
e.RepositoryItem = repositoryItemForVAL_VALUE;
}
}
To use a specific editor for inplace-editing only, you should handle the CustomRowCellEditForEditing event.
Please also carefully read the Remarks section of the GridView.CustomRowCellEdit event documentation which clearly describes how this event works.

Change datagridview cell value in edit mode

I have a cell in datagridview in which I display time in a custom format. I need when used enters edit mode (for example by double-click), I need to change the string value to integer representing the time in minutes.
When I try to change the cell value in "CellEnter" event, it doesn't seem to respond. Actually it doesn't seem to change the cell value pretty much inside any event.
Please don't mind the details of converting time to string and vise versa, my question is how can I successfully change the content of a cell when user double-clicks on it.
Edit (code + solution):
What I did is use another column to store the actual value (without formatting). On cell formatting of that column I'm passing the value to custom format function to fill my column.
private void gridview_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
if (e.ColumnIndex == 3 && e.Value != null && e.Value.ToString() != "")
{
//fill the unbound textbox column (5) from raw value column (3)
string newValue = TimeAttendanceHelper.FormatHourlyDuration(e.Value);
gridview.Rows[e.RowIndex].Cells[5].Value = newValue;
}
}
And then thanks to TaW, on CellBeginEdit I am showing the raw value to edit it:
private void gridview_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
if (e.ColumnIndex == 5)
{
//on editing, use the value from raw data column (3)
gridview.Rows[e.RowIndex].Cells[5].Value = gridview.Rows[e.RowIndex].Cells[3].Value;
}
}
And Finally when CellEndEdit, I reformat the new value:
private void gridview_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 4)
{
//update value both in columns 3 & 5
string newValue = tIME_SHIFTDataGridView.Rows[e.RowIndex].Cells[4].Value.ToString();
gridview.Rows[e.RowIndex].Cells[3].Value = newValue;
gridview.Rows[e.RowIndex].Cells[4].Value = TimeAttendanceHelper.FormatHourlyDuration(newValue);
}
}
When the cell is in edit mode you need to change the text in the edit control, usually a Textbox. You can get (and hold) a handle to it in the EditingControlShowing event:
TextBox editBox = null;
private void dataGridView1_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control is TextBox) editBox = e.Control as TextBox;
}
But using the CellEnter event is not a good idea as it will be called when scrolling or clicking around as well..
To catch the beginning of editing you use the BeginEdit event:
int yourEditColumn = 5;
private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
if (e.ColumnIndex == yourEditColumn )
{
string yourValue = "12345";
dataGridView1.Rows[e.RowIndex].Cells[yourEditColumn ].Value = yourValue;
if (editBox != null) editBox.Text = yourValue;
}
}

how to sum the column which is in the dataset and display in the footer

Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
try
{
int IndexTypeID = 5;
mobjORACLE = new DatabaseObjects.OracleDBCalls();
DataSet dsetPortfolio = mobjORACLE.GetORACLEDataSet(IndexTypeID, "v_indextypeid", "cv_1", "fn_getportfolio");
if (dsetPortfolio.Tables[0].Rows.Count > 0)
{
ViewState["gvPortfolio_DataSource"] = dsetPortfolio.Tables[0];
gvPortfolio.DataSource = dsetPortfolio.Tables[0];
gvPortfolio.DataBind();
gvPortfolio.Visible = true;
//dsetPortfolio.Tables[0].Rows[0]["cashreserve"];
//ViewState["gvPortfolio_DataSource"] = gvPortfolio.DataSource;
gvPortfolio.Attributes.Add("bordercolor", "#999966");
}
}
catch (Exception ex)
{
throw ex;
}
}
}
In gvPortfolio i got a datatable which has a column by name amount allocated. Now the question is, i need to sum up the column and display its result in the footer. Can somebody help me out in getting out of this.
You would use the GridView.RowDataBound Event.
Excerpt from Microsoft Documentation:
Before the GridView control can be rendered, each row in the control
must be bound to a record in the data source. The RowDataBound event
is raised when a data row (represented by a GridViewRow object) is
bound to data in the GridView control. This enables you to provide an
event-handling method that performs a custom routine, such as
modifying the values of the data bound to the row, whenever this event
occurs.
For example:
void gvPortfolio_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.Footer)
{
// Once you know you are in the footer row
// the sender object is the GridView and you can get the datasource
// loop thru the datatable adding up the values you want
// For example: let say column 3 have the number
// **** code is not tested - writing from memory ***
int total = 0;
int column = 3;
foreach(DataRow row in (DataTable)(sender.DataSource).Rows)
{
if (!row.IsNull(column))
{
// probably need more checking to make sure we have a valid integer
total += Convert.ToInt32(row[column]);
}
}
e.Row.Cells[column].Text = total.ToString();
}
}
Good morning I believe that this previous post should help you with what you are trying to accomplish.

CellFormating get curent row

I am using DataGridView CellFormating to format specified cells.
The code I am trying:
private void dgwPart_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (this.arts.Type == ArtType.Pak)
{
if (dgwPart.Columns[e.ColumnIndex].Name == "Discount")
e.Value = "";
}
}
The problem is that it changes the value for all column, but I only want that it changes the value for specified row. How do I manage it?
You can use e.CurrentCell to find whether it is the row you want, something like:
If (dvImages.CurrentCell.RowIndex == 10)
{
Debug.WriteLine("Do something")
}
If ((int)(dvImages.CurrentCell.Value) = 100)
{
...
}
* these should be within the cellformat, after you check the column.
you may need check the syntax, I just typed this from my header.

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