guys i am trying to get the index of a column with a specific column header.
Till now i got to
int index_of = grid_statement.Columns[the_name].Index;
But it throws a NullReference exception.
Is there any other ways to get that index ?
(the_name is a variable having the column header)
If your are trying to get column by it's name, then either your grid is null, or there is no column with name equal to the_name in your grid. In both cases you will not be able to get index of non-existing column. To avoid exception in case there is no column with provided name, you can check if column exists before trying to get its index.
var column = grid_statement.Columns[the_name];
int index_of = column == null ? -1 : column.Index;
If you are trying to get column by it's header text (which is not same as column name) you should search for column with same header. And if column was found, get it's index:
var column = grid_statement.Columns
.Cast<DataGridViewColumn>()
.FirstOrDefault(c => c.HeaderText == the_name);
int index_of = column == null ? -1 : column.Index;
try this it will helps you
int index_of = grid_statement.CurrentRow.Cells["ColumnName"].ColumnIndex;
You are probably trying to access the columns collection before binding the data source. At this time gridview wont have any columns. Assign dataSource and bind the grid and then check the index of column.
grid_statement.DataSource = dataTable;
grid_statement.DataBind();
int index_of = grid_statement.Columns[the_name].Index;
To avoid exception you should first check if you got column then get its index.
int index_of = -1;
if(grid_statement.Columns[the_name] != null)
index_of = grid_statement.Columns[the_name].Index;
Related
I have a DataTable with the Column name "Part Number" and various other columns. I want to grab all of the elements that are in the column "Part Number". This column can sometimes be in a different position so I can't just assign a particular Item Array index. I want to use LINQ to do it.
Right now, I just grab everything in the first column. However, I want to set this to grab the data according to the column heading.
var parts = from row in dataTable.AsEnumerable()
where true != string.IsNullOrWhiteSpace((row.ItemArray[0] == DBNull.Value)
? string.Empty
: row.ItemArray[0].ToString())
select row.ItemArray[0];
You can index a DataColumnCollection by a DataColumn, like this:
// Find the DataColumn by column name
string columnName = "Part Number";
DataColumn partNumber = dataTable.Columns[columnName];
var parts = from row in dataTable.AsEnumerable()
where !string.IsNullOrWhiteSpace(row[partNumber].ToString())
select row[partNumber];
Let the DataTable worry about finding the index inside the ItemArray. All you have to know is the column name.
For more information, see the documentation.
Can I do this in C# with DataTable.Select(filterStatement);?
Or should I use Linq?
I have a SQL query that returns a DataTable dt2 with two columns, [Username] and [LastUpdated].
I want to get a string out of the [LastUpdated] column where the [Username] column is equal to a string.
Just in case this matters, both data types are set to varchar(50) in the SQL table.
I would post a picture but I can't yet, first post, the datatable is just
Username|LastUpdated
....admin2 | 2015-04-27...
In this case if I could just get the value of the second column where [Username] = 'admin2'.
I have tried the following in the C#:
string timestamp = "";
DataRow[] dt2result = dt2.Select("Username = 'admin2'");
timestamp = dt2result[1].ToString();
And I get
System.IndexOutOfRangeException: Index was outside the bounds of the array
I have tried to just use DataRow dt2result = dt2.Select("Username = 'admin2'"); without the bracket [ ] but I get
"Cannot implicitly convert type 'Sytem.Data.DataRow[]' to 'System.Data.DataRow'"
I have tried different indexes like dt2result[0] and dt2result[1][0] etc, as well as dt2result.GetValue(0)
I know this is a basic question, but please answer it comprehensively!
Thanks in advance!
DataRow dt2result = dt2.Select("Username = 'admin2'").First();
will get you the correct row (I assume). Then get the correct column with:
var timestamp=dtresult[1].ToString();
The following should work as well:
var timestamp=dt2.Select("Username = 'admin2'")[0][1].ToString();
In this case if I could just get the value of the second column where
[Username] = 'admin2'.
You have multiple ways of getting LastUpdated column value.
With your current code:
DataRow[] dt2result = dt2.Select("Username = 'admin2'");
You will get an array of DataRow back, you can check the length of your array and access the first row like:
DataRow firstRow = dt2result[0];
and to select value of second column you will need:
var lastUpdatedValue = firstRow[1];
Then there is a LINQ option
var lastUpdatedValue = dt2.AsEnumerable()
.Where(r => r.Field<string>("Username") == "admin2")
.Select(r => r.Field<string>("LastUpdated"))
.FirstOrDefault();
I am using r.Field<string>("LastUpdated") since you have varchar data type for LastUpdated column. Just as a side note, it would be better if you use DateTime specific types for storing date and time values.
I have a GridView
How do I get a value of a column for a given row.
I tried the following but it only gives the row number instead of the value:
int selRowIndex = ((GridViewRow)(((System.Web.UI.WebControls.CheckBox)sender).Parent.Parent)).RowIndex;
you are looking for the contentnot the index
var cellText= ((GridViewRow)(((System.Web.UI.WebControls.CheckBox)sender).Parent.Parent)).Cells[0].Text;
and then convert it to int
I am trying to get the value from a GridView and save it as a Session variable.
I know the column name and there is only ever one value in the GridView. What is the best way to select it and save as the Session variable?
The column name is CustomerID and the value is always a int.
if there is one column and one row in the GridView you can try below.
Session["MySessionValue"]= GridView1.Rows[0].Cells[0].Text;
but exception can be thrown when you access by index if there is no records in the GridView. So better to check GridView1.Rows.Count First and get the value
This is not a proper way to do this, you better hardcode the cellindex but anyways a little longer version of Damith's answer
if (GridView1.Rows.Count > 0)
{
int indexofcolumn = 0;
foreach (DataControlField column in GridView1.Columns)
{
if (column.HeaderText == "CustomerID") break;
indexofcolumn++;
}
Session["CustomerID"] = GridView1.Rows[0].Cells[indexofcolumn].Text;
}
You can set a DataKey for GridView as CustomerID and select by:
int ID = Convert.ToInt32(GridView1.DataKeys[indx].Value);
indx is Row Index in GridView..
I have some code which sets the value of cells in a DataRow by column name i.e.
row["ColumnName"] = someValue;
I want to also set the value for this row in the column immediately to the right of the one found above. Clearly if I was getting the cell by index rather than by column name this would be easy. So is there a way of getting the column index from the column name thus allowing me to do:
row[index + 1] = someOtherValue;
i.e. do I need create some kind of dictionary of column index and column names when the table is initially created, or can I get the index from the column name later on without doing this?
You can use DataColumn.Ordinal to get the index of the column in the DataTable. So if you need the next column as mentioned use Column.Ordinal + 1:
row[row.Table.Columns["ColumnName"].Ordinal + 1] = someOtherValue;
Warning:
This code returns the next column, so the one after ColumnName, as requested in the question.
Try this:
int index = row.Table.Columns["ColumnName"].Ordinal;
You can simply use DataColumnCollection.IndexOf
So that you can get the index of the required column by name then use it with your row:
row[dt.Columns.IndexOf("ColumnName")] = columnValue;
I wrote an extension method of DataRow which gets me the object via the column name.
public static object Column(this DataRow source, string columnName)
{
var c = source.Table.Columns[columnName];
if (c != null)
{
return source.ItemArray[c.Ordinal];
}
throw new ObjectNotFoundException(string.Format("The column '{0}' was not found in this table", columnName));
}
And its called like this:
DataTable data = LoadDataTable();
foreach (DataRow row in data.Rows)
{
var obj = row.Column("YourColumnName");
Console.WriteLine(obj);
}