C# Datatable woes - c#

I have a database command that populates a DataTable I want to get the value of an entry in the Datatable, based on, A: The numeral index of the row, and b, the string name of the column. That's all I want, how is that possible?

yourDatatable.Rows[rowIndex]["columnName"] should work

myTbl.Rows[0]["b"];
A is not a row index.

DataTable dt = GetData();
var result = dt.Rows[RowIndex]["MyColumnName"];
The RowIndex is an indexed property of the datatable which returns a DataRow. "MyColumnName" is an indexed property of the DataRow, returning the value as an object.

Related

Getting a Value in the First index of a TableAdapter in C#

Am trying to get a a Zero indexed Value from a column in the TableAdpter but it has refused , how can i retrieve a value in the Column index Zero , below is my code :
LoginTableAdapter l = new LoginTableAdapter();
string res = l.GetData("mueat", "1234").Rows[0].ToString();
And my table which is attached to the TableAdapter is as below , it's one column and i want to get the value t which is in a Zero index in the column access:
If we assume l.GetData("mueat", "1234") returns a DataTable, like so:
DataTable table = l.GetData("mueat", "1234"); // the dataTable
then this:
DataRow row = table.Rows[0]; // first row;
will only give you the first row out of the DataRowCollection's indexer
As we can see on the DataRow type, it has an indexer as well, giving access to the columns in the DataRow instance.
object columnValue = row[0]; // first column
You can now cast the object value to the correct type or call ToString on it to convert it to its string representation.
Putting this all back together in your compact one-liner you will get:
string res = l.GetData("mueat", "1234").Rows[0][0].ToString();

Filtering columns in datatable

I have a datatable with multiple columns. I want to filter the columns for which i do:
newDatableName= OldDt.ToTable(false,"col1","col2");
Now suppose, I want to specify the column names dyanamically i.e put all the column names in a string and then Do:
string colnames= "col1,col2";
newDatableName= OldDt.ToTable(false,colnames);
I tried the above but it does not work. I even tried:
string colname= "\"col1\",\"col2\"";
but it considers the string of column names as one column and gives the error that no such column present.
Any help appreciated.
I suppose that you are using the DataView.ToTable method (so OldDT is a DataView not a DataTable).
In this case you need to pass an array of your column names
string[] colnames = new string[] {"col1", "col2"};
newDatableName= OldDt.ToTable(false,colnames);
you can use Steve's answer, if don't like defining a new array try this:
string colnames="col1,col2"
newDatableName=OldDt.ToTable(colnames.Split(',');
DataTable.DefaultView.ToTable(bool, Params string[] ColumnNames);
The above Method creates and returns a new DataTable based on rows in an existing DataView.
You have to passes two parameters to this function.
If true, the returned DataTable contains rows that have distinct values for all its columns. The default value is false.
A string array that contains a list of the column names to be included in the returned DataTable . The DataTable contains the specified columns in the order they appear within this array.
For Example:
DataTable NewTable = dt.DefaultView.ToTable(false, "StartDate", "FinishDate", "ItemName", "AssigneeNames", "ProjectName", "PercentComplete");

how to get a value from a filtered values of dataview in C#?

I have a filtered data view, from which I have to extract the values. Problem is that when I do this, I am getting the values from non filtered data also.
dv1.RowFilter = "collegeno=" +i;
for(int k=1;k<dv1.count;k++)
{
//inserting data in database; there is column in database table; I am inserting into it;
dv1.Table.Rows[k]["roomno"]);
}
For ex: The total no. of rows in DataView is 200;
When i=1 I have 30 records;
If I supply k=4, then I should get fourth row from this 30 records.
But I am getting 4th row of the 200 records..
The code you have written is accessing the main table using the code block dv1.Table.
Instead try as this
dv1[k]["roomno"]
This code works on DataView, on which the filter is applicable.
If you use DataView.Table then it will access the non-filtered results.
Reference Link: MSDN - DataView.RowFilter
If I supply k=4, then I should get fourth row from this 30 records.
But I am getting 4th row of the 200 records..
That's because you're querying the table, not the view. Instead you should do this:
dv1.RowFilter = "collegeno=" +i;
object value = dv1[k]["roomno"];
Depending on what you need, you might want to use the DataTable.Select method instead of a DataView:
var rows = table.Select("collegeno=" +i);
object value = rows[k]["roomno"];
DataTable dt = dv.ToTable();
for(int k=1;k<dt.Rows.Count;k++)
{
dt.Rows[k]["roomno"];
//dv1.Table.Rows[k]["roomno"]);
}

DataGridView show Int instead of Double values

I'm using an SqlServerCe database and a dataset. There's no problem to transfer data to database. There Are two double value columns in the database displaying values properly. When I fill DataGridview from database with these values, the double values apperaring as Int. Here's the part of code if necessary.
if (rdb_FillData.Checked)
{
dbDataSet.AppDataDataTable dTable = new App1.dbDataSet.AppDataDataTable();
AppDataTableAdapter.Fill(dTable);
AppDataBindingSource.DataSource = dTable;
AppDataDataGridView.Refresh();
}
You cannot change the DataType after the Datatable is filled with data. However, you can clone the Data table, change the column type and load data from previous data table to the cloned table as shown below.
Sample code to change datatype of a column to Decimal
DataTable dtCloned = dt.Clone();
dtCloned.Columns[0].DataType = typeof(Decimal);
foreach (DataRow row in dt.Rows)
{
dtCloned.ImportRow(row);
}
check your values in dTable, if they are true it's possible you have created your columns manually and column types are wrong.
if dTable values are wrong maybe your AppDataDataTable column types are wrong.

How to get Column Value of a DataRow in a Datatable

I have a DataTable which is bind to dataGridview in my code.
When I get datas from database, the gridview works fine. it fills with data.
What I want to do is getting the primary key value of the specified row.
Ex:
PK Address Phone
1 xxxyyyzzz... 1234567
2 aaabbbccc... 2345678
What I want is this. User will click on any row, then click on a button to add some stuff.
Then I will get PK value, and do other stuffs.
How can I do it?
Hmm can you specify how and when you are talking about getting this value?
You can do this:
int index = dt.Rows.IndexOf(row);
But I am not sure what the point of that would be, if you already have the specified row, why can't you just get the PK via row[columnName]?
But this is more resource intensive than just looping through with a for loop.
Do you need this before or after binding to the dataGridView? If you need to get the value from the dataGridView row that is different.
For your edit:
You would can get the selected row like so:
if (yourDataViewGrid.SelectedRows.Count == 1)
{
Int pk = yourDataViewGrid.Rows[yourDataViewGrid.SelectedRows[0].Index].Cells["PK"].Value.ToString();
}
If you are doing it by some other method like using a checkbox to select a row, you would do this:
foreach (DataGridViewRow row in YourDataGridView.Rows)
{
if ((Boolean)((DataGridViewCheckBoxCell)row.Cells["CheckBoxName"]).FormattedValue)
{
Int pk = rows.Cells["PK"].Value.ToString();
}
}
The DataGridView control binds to a DataTable using the DataView class. You can use something like this to get the DataRow of a DataGridViewRow
var vrow = (DataRowView)grid.Rows[12].DataBoundItem; // get the bound object
var drow = vrow.Row; // the Row property references the real DataRow
where 12 is the index you are looking for. Sometimes it helps to set the DataSource property to a DataView explicitly and keep a reference to it on your form. The view will know the sorting of the data too
var view = new DataView(table);
grid.DataSource = view;

Categories