My datadsource is querying the table for a varchar column, that either comes out empty or comes out something like "1,2,3,4,5".
On the RowDataBound event I want to test if the string is not empty so I can substitute that string with an image or whatever.
But
e.Row.Cells[0].Text.Length
returns 9 for the populated Cells (and this is correct), and returns 6 for the empty ones.
Can someone explain this to me? It's not just in this one column.
Instead, always use String.IsNullOrEmpty method to check for empty strings.
So, in your current problem it would be:
if String.IsNullOrEmpty(e.Row.Cells[0].Text.Trim())
{
// code in here would execute when the Text property is empty/null
}
Related
I am storing the value of gridview into a string. I have two lines of code.
string UserName = GridView1.Rows[e.RowIndex].Cells[4].Text.ToString(); 1
string UserName = GridView1.Rows[e.RowIndex].Values["UserName"].ToString(); 2
Both will have same Values. Which is the better option to use 1 or 2 ?
I prefer to use the second one, so that if the column index change in time, it's not necessary to rewrite all indexes in code again.
The second one:
Its more future proof, changing the structure of the table would
require you to change the cell index.
Its easier to read, without looking at the variable we can see you are asking for the usernames, We don't have to check what values are in the 4th column.
I have this Datagridview, where I'm inserting a new row, but the value for the column
expected_date, it is getting a null value in the program, when in fact I have typed in 01/01/2099,
I've tried inserting manually in my code and it works, but when I'm doing something like :
dataGridView2[fieldIndex, rowIndex].Value
in order to grab 01/01/2099 from the Datagridview and use it in my code, it just returns null or "" (Empty String).
I'm also just not sure why it's only for the column that uses a date that causes the trouble.
I would like to create a cell for the datagridview that would accept a Int64 value in order to sort.
Additionally that cell will display an extra value that is the difference of the current value with a reference value I have outside the datagridview.
I could do it as string but the sorting will not be correctly handled because it would look like 1, 10, 11, 2.... and so on.
So I thought that if I could create a custom cell and define the cell value the long and display a string it would be great... but I'm not sure if this can be accomplished....
Does someone know how can this be accomplished in a simple way? Note that I am loading the datagridview manually but I am defining the column types to allow sorting.
One fairly easy way to do this is to use the DataGridView's SortCompare event. Use the event to check that the column being sorted displays your custom data and if so extract the number portion of that data and do your sort on it.
Below I have an example:
private void dataGridView1_SortCompare(object sender, DataGridViewSortCompareEventArgs e) {
if (e.Column.Index == 1) { // This is your custom data's column.
// Extract the numeric values from the cells being compared for the sort.
// BEWARE: code assumes you'll always be able to extract a long from the cell contents.
long cell1NumericValue = Int64.Parse(e.CellValue1.ToString().Split(' ')[0]);
long cell2NumericValue = Int64.Parse(e.CellValue2.ToString().Split(' ')[0]);
// Compare these numeric values to determine how to sort.
e.SortResult = cell1NumericValue.CompareTo(cell2NumericValue);
e.Handled = true;
}
}
Assumptions:
- that the column with your custom data is at column index 1
- that your custom data consists of a number followed by at least one space
My code also assumes that the conversion of the cells' value will never throw an error. It's possible that your data includes values that would cause this conversion to fail. What you could do in that case is validate your data before the conversion (that it's not null, etc.) and if of the validation fails set the cell's numeric value for sorting purposes to -1 or something so it's always lower than valid values in other cells. (I hope that made sense).
Applying these types of sorts is pretty well described in this MSDN article. You'll probably want to take a look. One of the examples show what you can do in the case of ties (the example shows sorting on another column as the sort tiebreaker).
I have a form with a DataGridView widget and I need to get the index of the column with the selected name.
For example, let's say that I have a table with 2 columns: Name, Surname. I need a way to get index of the column name. The problem is that it changes all the time depending on the DataSource but that column always has the same name "Name".
Does anyone know how to solve the problem?
To retrieve a DataGridView column by name you simply reference it through the columns collection indexer:
datagridview1.Columns["columnName"]
Then you can get the column index from that column:
datagridview1.Columns["columnName"].Index;
Do note that if you use an invalid column name then this reference will return null, so you may want to check that the column reference is not null before using it, or use the columns collection .Contains() method first.
If I am right, e.ColumnIndex will also work for this. you can check the MSDN Documentation here
You can get the index by using the Index property of the DataGridViewColumn widget, as such:
ColumnName.Index
This avoids the need for checking whether the column name is valid at runtime as it will generate a compilation error if the column does not exist. This also makes refactoring easier.
I recommend you give the columns a sensible name (for example DCOL_SomeName) so that you can easily distinguish them. Including the name of the DataGridView widget would help if you have multiple DataGridView widgets on the same form.
create a static class below the code
public static class MyTools
{
public static int IndexByName(this DataGridView dgv, string name)
{
foreach(DataGridViewColumn col in dgv.Columns)
{
if(col.HeaderText.ToUpper().Trim() == name.ToUpper().Trim())
{
return col.Index;
}
}
return -1;
}
}
and then call it with your dataGridView
int index = datagridview1.IndexByName("columnName");
I have found it safer to use the column object's Name property, instead of using the column name as a string, because this allows for more consistent code refactoring in the future.
datagridview1.Columns[column1.Name].Index;
Also, it is important to first make sure the column is not null and, as others have said, that it is contained within the datagridview.
I'm writing a front end to a database, presenting options as comboboxes. And I need to be able to return nulls to the database.
I have a solution at the moment which involves 'fudging' a record into the query to populate the Datatable, then detecting the selection and hard coding null into my update statement if this item has been selected.
--GetDataByAvailableTechs query
SELECT tblLEMSCredentialsId, TechNumber
FROM tblLEMSCredentials AS aLEMSCreds
UNION ALL
SELECT '99999' AS Expr1, '<NONE>' AS Expr2
.
//populate combo box
BV_LEMSHIPDataSet.tblLEMSCredentialsDataTable dtAvailableTechs = taLEMSCreds.GetDataByAvailableTechs(selectedSerial);
cboTechNumber.DataSource = dtAvailableTechs;
.
//Save back to DB
if (lemsCredsID == 99999)
{
taDevice.UpdateQuery_Restage(null, selectedSerial);
}
else
{
taDevice.UpdateQuery_Restage(lemsCredsID, selectedSerial);
}
Can anyone suggest a better way of doing this please? I need to make the application cope with another 5 similar fields and don't want to create a multitude of if else versions of my update.
G
In the past I've used a similar approach but used minus numbers for the NULL values - that way you can you treat anything less than zero as NULL in one if statement.
This assumes that your ID's in the table are always positive though :)
Null object pattern. Make it return an empty string for the UI and provide a method call to extract the value when updating the database. In normal cases this will return your true value but the null object will override this behaviour to give you your null.
No magic numbers required and all you need to do is add this value to the start of the "bindable values" when you bind your control to the datasource.
You may put an string value as the combobox 'null value', for example: "thenullvalue" then parse combobox value to nullable int type (int?). For proper selection you will get the desired value, for 'null selection' you will get null (parsing "thenullvalue" to int will give you null) :)
Then save the value to database just as:
int? lemsCredsID = parseInt(combobox.Value);
//Save back to DB
taDevice.UpdateQuery_Restage(lemsCredsID, selectedSerial);
Depending of your db provider you might also need to convert nullable type null value to DBNull, like this:
taDevice.UpdateQuery_Restage((lemsCredsID==null ? DBNull : (int)lemsCredsID), selectedSerial);
Hope this helps.
If the value is intended to be null, pass null to the database would be a good solution, this reduces the extra logic handling for special values for nulls and it can be quite risky and ambiguous.
The view or application layer should be able to handle null either returned from database or passing into it.
e.g. you can convert null to string.Empty before binding the control as well as you can convert string.Empty to null before passing into the database.