how to get specific column value after filling dataset with tableadapter - c#

for example:
table1 has two columns "col1" and "col2"
this.table1TableAdapter.FillByParam(appDataSet.table1,param);
this returns 1 row
how to set col1 and col2 values to variable?
It would be great if someone post example with code.
Thanks.

This line fills a given DataTable from the query that is specififed as SelectCommand in the TableAdapter. So you say that it just contains a single record?
You can use FirstOrDefault to get that DataRow. Since it's a strongly typed DataTable you have an autogenerated DataTable and DataRow with typed properties and names that are the same as the ctypes and names in database.
So assuming you have two Label controls which Text properties you want to set from the two properties in the row:
appDataSet.table1Row row = appDataSet.table1.FirstOrDefault();
if(row != null)
{
Label1.Text = row.col1;
Label2.Text = row.col2;
}

Related

Sorting numeric column in datagridview

I am using a datagridview to show data in csv file. One of the column in datagridview in of numeric type [Column name: ID].
I am using autosort method of datagridview(sorting by clicking column header).
This works well for all the columns except this numeric column.
This column contains numbers 1 to 55
What I am getting now is after sorting is:
1,10,11,12,13,14,15,16,17,18,19,2,20,21,22,23,24,25,26,27,28,29,3,30,31...
...and so on. what I want is:
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,...
Please help.
Thanks in advance.
You can use the event SortCompare like this:
private void dataGridView1_SortCompare(object sender, DataGridViewSortCompareEventArgs e) {
//Suppose your interested column has index 1
if (e.Column.Index == 1){
e.SortResult = int.Parse(e.CellValue1.ToString()).CompareTo(int.Parse(e.CellValue2.ToString()));
e.Handled = true;//pass by the default sorting
}
}
Build your DataTable:
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(Int32));
dt.Columns.Add("Name");
dt.Columns.Add("ForeName");
I am using these columns due to the fact that I don't know what data you are storing.
After reading your csv-file you have to iterate through the data. Considering you have your data stored in a String array (String[][] arr) with the inner ArrayLength of 3 (ID, Name, ForeName).
for(int i=0;i<arr.Length;i++)
{
DataRow row = dt.NewRow();
row["ID"] = Convert.ToInt32(arr[i][0]);
row["Name"] = arr[i][1];
row["ForeName"] = arr[i][2];
dt.Rows.Add(row);
}
DataGridView dgv = new DataGridView();
dgv.DataSource = dt;
I hope this helps, it's a sample Code.
The reference to DataTable: https://msdn.microsoft.com/de-de/library/system.data.datatable(v=vs.110).aspx
EDIT
I just read that you already have a DataTable as result. You can build another DataTable as I did and iterate through your Data and convert the ID to an Integer. Please don't forget to set the Columns Type:
dt.Columns.Add("ID", typeof(Int32));
Well, your column is not numeric, but a text column that contains numeric string values. There's a huge difference! A real numeric column would apply numeric sorting, while your column uses alphanumeric sorting.
I'd try to actually change the underlying data type to int instead of string or apply manual sorting as suggested by lem2802.
Please add some information about how you fill the data grid view. Maybe that can help find an easier way than implementing a manual sort comparison.
According to your comment you create a DataTable as the data source for the grid view. You need to make sure that the column(s) containing numeric values also have a numeric type. In the code where you create the table and its columns, do something like this:
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(Int32));
... // Other columns
Later when you create the rows based on the content of your CSV file, make sure to fill each row so that the value for the ID column actually is an int:
DataRow row = table.NewRow();
row["ID"] = Convert.ToInt32(idValueFromCSV);
... // Other columns
That way you'll get what you want without implementing custom sorting.

C# getting values from DataTable or BindingSource

I have a labels that need values retreieved from a Database.
I am able to query the database but how can I extract values from a DataTable and place them in the appropiate labels
Thanks
In DataTable you have rows and columns. To select a particular cell you need to do this:
label1.Text = dataTable[0][0];
This will set the label1 text to Row 0, Column 0 value.
To iterate through each row use:
foreach(DataRow row in dataTable.Rows)
{
Console.WriteLine(row["ColumnName1"]);
Console.WriteLine(row["ColumnName2"]);
Console.WriteLine(row["ColumnName3"]);
Console.WriteLine(row["ColumnName4"]);
}
This will print values for columns against each row. In this code you need to replace string for columnname (e.g. ColumnName1) with your column names
Example of how you retrieve a value from the first row and the column named "MyFirstColumn":
label1.Text = myDataTable.Rows[0]["MyFirstColumn"]

C# datagridview combobox column datasource from list/dictionary/datatable

I've got a datatable and one column is an integer ID foreign key to another database table.
I've got a datagridview and i'd like to use a combobox column to allow user to change value. But instead of using the integers, it would be great to use the names.
I've tried creating a simple struct with public members int ID and string Name; a dictionary and looked into enums (however values not known at compile time) but not got anything to work yet.
I was able to populate the combobox with struct values, but not able to programmatically set the selected item/index; ie, if ID "5" is in the datatable, set the combo box selected item to the struct that has an ID of 5.
So to be clear i'm wanting:
gridview datasource's fk ID's
1
2
3
Foreign Key table:
ID Name
1 Name 1
2 Name 2
3 Name 3
Datagridviewcombobox column should be loaded with three items; should display as "Name 1, Name 2, Name 3". Based on the gridview datasource's FK id, the selected item for each should match.
You can set the DataGridViewComboBoxColumn.DataSource property, and then use the ValueMember and DisplayMember properties to determine what is shown in the ComboBox. Easiest is probably to load your FK values into DataTable and use that as the data source. For your example:
// assuming your DataGridViewComboBox column is fkCol
// and your fk values are in a DataTable called fkTable
fkCol.DataSource = fkTable;
fkCol.ValueMember = "ID";
fkCol.DisplayMember = "Name";
I am not sure how you are binding your DataGridView to your initial DataTable, but you can associate the DataGridViewComboBox column with a specific column in your original DataTable using DataPropertyName:
fkCol.DataPropertyName = "ColumnName";
DataAccessLayer dal = new DataAccessLayer();
DataTable movies = dal.GetMovies();
gvMovies.DataSource = movies;
gvMovies.AllowUserToAddRows = false;
gvMovies.AllowUserToDeleteRows = false;
//Create the new combobox column and set it's DataSource to a DataTable
DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
col.DataSource = dal.GetMovieTypes(); ;
col.ValueMember = "MovieTypeID";
col.DisplayMember = "MovieType";
col.DataPropertyName = "MovieTypeID";
//Add your new combobox column to the gridview
gvMovies.Columns.Add(col);

Show only selected rows in Gridview

I have DataTable object and am binding it to a gridview in C#.
I have 3 columns in the datatable, say "Flag", "Name", and "Value".
What I want to accomplish is that I want to only show the rows where "flag" fields are set to 0.
So say if I have two rows in the table,
Flag Name Value
------------------
0 tom 100
1 Jane 200
And, I only want to show "tom" and "100" on the gridview.
Is there any way I could do this without creating a new datatable?
Thanks.
Here is an example :
DataTable table = DataSet1.Tables["Orders"];
// Presuming the DataTable has a column named Date.
string expression;
expression = "Date > #1/1/00#";
DataRow[] foundRows;
// Use the Select method to find all rows matching the filter.
foundRows = table.Select(expression);
// Print column 0 of each returned row.
for(int i = 0; i < foundRows.Length; i ++)
{
Console.WriteLine(foundRows[i][0]);
}
You can see example Here
Probably you can take the same Datatable like : table = table.Select(...);
try creating a DataView for your DataTable and send it to your GridView instead of the DataTable. see http://msdn.microsoft.com/en-us/library/system.data.dataview.aspx

How can we copy the column data of one DataTable to another, even if there are different column names between DataTables?

I have two DataTables.
First is
DataTable NameAddressPhones = new DataTable();
with Three columns Name, Address and PhoneNo.But I only want two columns Name and Address data so I want to copy those columns (with data) to the new DataTable.
DataTable NameAddress = new DataTable();
For that I do
foreach (DataRow sourcerow in NameAddressPhones.Rows)
{
DataRow destRow = NameAddress.NewRow();
foreach (string colname in columns)
{
destRow[colname] = sourcerow[colname];
}
NameAddress.Rows.Add(destRow);
}
I clear the NameAddressPhones(first) DataTable every time there are new records inserted in the table. And every time there will be the same number of columns but the column names will be different like Nm instead of Name, Add instead of Address.Now the problem is the second DataTable already has column names Name and Address and now I want to copy the columns data of Nm and Add to the second DataTable but the column names are different than the column names of the second DataTable. So even if there are different column names I want to copy Nm column data of first DataTable to the column Name of second DataTable and column Add data of first DataTable to column Address of second DataTable.
In short how can we copy column data from one DataTable to another even if there are different column names of both DataTables like Nm is the column name of first DataTable and Name is the column name of second DataTable then the data of the column Nm should be copied to the column Name.
Here's the simplest way:
foreach (DataRow sourcerow in NameAdressPhones.Rows)
{
DataRow destRow = NameAdress.NewRow();
destRow["Name"] = sourcerow["Nm"];
destRow["Address"] = sourcerow["Add"];
NameAdress.Rows.Add(destRow);
}
Automation is great when it's available. When it's not, you have to map source columns to destination columns in some manner.
If the columns are in the same order in both tables, you could just reference the values by ordinal instead of column name, but that's such a bad idea I'm not even going to post any code for it.
Use column index number rather than names:
destRow[0] = sourcerow[0]; // for column 0 = "Name" or "NM"
If I've understood your question right, then the way this is usually done is by using stored procedures. You have the same stored procedures in both databases, but the implementation is specific to the table schema of each database. This allows you the abstraction you need.

Categories

Resources