Grid view Row Data Bound putting data in a particular cell - c#

I have 3 tables Customer, Address and Matching_Customer_Address.
Customer has column Name and Address has column City. They have some other columns as well but I don't need them. The Name and the City column contains this kind of data.
NAME City
---------- -----------
John New York
---------- ----------
Karin Hamburg
--------- ----------
Jona Tokyo
--------- ----------
Martin
Matching_Customer_Address contains the IDs of both tables which have a match between them.
I have a Grid view and I bind this GridView1 with datatable dt. dt is in this format:
Data table dt first column is "Match" and rest of the columns are from Address.City and rows are from Customer.Name.
As Gridview1 is bind with dt so grid view is like this.
Match | New York| Hamburg | Tokyo |
----- | --------| ------- | ------ |
John | | | |
----- | ------- | ------- | ------ |
Karin | | | |
----- | ------- | ------- | ------ |
Jona | | | |
----- | ------- | ------- | ------ |
Martin| | | |
----- | ------- | ------- | ------ |
Now by using the table Matching_Customer_Address I want to put a character "X" in GridView1 cell. I am using RowDataBound event to do this task but I don't know how I should proceed.
I am trying to do
e.Row.Cells[].Text = "X";
I know how to access the Matching_Customer_Address table here But I don't know how to put an X in a particular cell if a match is found. I am very new to C#.
Here is the code to bind data with gridview.
DataTable dt = new DataTable();
SqlDataAdapter da_Customer, da_Address;
DataSet ds_Customer = new DataSet();
DataSet ds_Address = new DataSet();
SqlConnection con;
con = new SqlConnection("Data Source=local;Initial Catalog=Test;Integrated Security=True");
da_Customer= new SqlDataAdapter("Select Name from Customer ", con);
da_Customer.Fill(ds_Customer, "Name");
da_Address = new SqlDataAdapter("Select City from Address ", con);
da_Address .Fill(ds_Address, "City");
int lengthofAddress = ds_Address.Tables[0].Select("City is not null").Length;
string[] getCols_City = new string[lengthofAddress];
int lengthofCustomer = ds_Customer.Tables[0].Select("Customer is not null").Length;
string[] getRows_Customer = new string[lengthofCustomer];
//added first column of dt.
dt.Columns.Add(new DataColumn("Name", typeof(string)));
// This loop is getting rows from table City and adding them as column of dt.
for (int x = 0; x < (lengthofAddress); x++)
{
string mystring = (ds_Address.Tables[0].Rows[x]["City"].ToString());
getRows_Customer[x] = mystring;
dt.Columns.Add(getRows_Customer[x]);
}
// This loop is getting rows from table Customer and adding them as Rows of dt.
for (int x = 0; x < (lengthofCustomer); x++)
{
getRows_Customer[x] = (ds_Customer.Tables[0].Rows[x]["Name"].ToString());
dt.Rows.Add(getRows_Customer[x]);
}
GridView1.DataSource = dt;
GridView1.DataBind();
Aspx Code is here :
<asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#3366CC"
BorderWidth="1px" CellPadding="4" Font-Names="Arial" Font-Size="Small" Width="100%"
BorderStyle="None" OnRowEditing="GridView1_RowEditing" onrowdatabound="GridView1_RowDataBound" >
<HeaderStyle CssClass="GridviewScrollHeader" />
<RowStyle CssClass="GridviewScrollItem" />
<PagerStyle CssClass="GridviewScrollPager" />
</asp:GridView>

Put the logic to find matches into the data table building logic that you posted, like this:
// This loop is getting rows from table Customer and adding them as Rows of dt.
for (int x = 0; x < (lengthofCustomer); x++)
{
// Build the pieces of data for your row here
// Name
// Loop through each city
for (int y = 0; y < (lengthofAddress); y++)
{
// Determine if each city is a match or not,
// if so then put "X" in that row's cell here
}
}
Now when you bind your grid with the data table, you will not need to handle the RowDataBound event, because the X will be in the right cell(s) already.
UPDATE:
To put values into a new data table row, you need to create a new row and then apply the cell values via the index of the row, like this:
DataRow row;
// Create new DataRow objects and add to DataTable.
for(int i = 0; i < 10; i++)
{
row = YourDataTable.NewRow();
row["Name"] = theName;
// Loop through each city
for (int y = 0; y < (lengthofAddress); y++)
{
// Determine if each city is a match or not,
// if so then put "X" in that row's cell here
if(match)
{
row[y+1] = "X";
}
}
YourDataTable.Rows.Add(row);
}
UPDATE 2:
If the rows for each person in the match column already exist, then loop through each row like this:
foreach(DataRow row in TheTable.Rows)
{
// Loop through each city
for (int y = 0; y < (lengthofAddress); y++)
{
// Determine if each city is a match or not,
// if so then put "X" in that row's cell here
if(match)
{
row[y+1] = "X";
}
}
}

Related

Comparing each column value in DataRow without using for/each loop

Is there a way to achieve the same below output without using for/each loop? (using lambda expression?)
DataRow leftDataRow = GetReferenceDataRow();
DataTable table = GetTableForComparison():
List<NonMatchingValue> listColumnsWithDiscrepancies = new List<NonMatchingValue>();
foreach (DataRow row in table.Rows)
{
for (int index = 0; index < table.Columns.Count; index++)
{
if (leftDataRow[index].ToString() != row[index].ToString())
{
listColumnsWithDiscrepancies.Add(new NonMatchingValue {
FieldSource = leftDataRow.Tables.Columns[index].ColumnName,
FieldTarget = row.Table.Columns[index].ColumnName
ValueSource = leftDataRow[index].ToString(),
ValueTarget = row[index].ToString(),
IsEqual = leftDataRow[index].Equal(row[index])
});
}
}
}
The structure/number of columns of leftDataRow and rows in the table is identical.
// Sample Output:
FieldSource | FieldTarget | ValueSource | ValueTarget | IsEqual
-------------------------------------------------------------------------------
Column1 | Column1 | X | Y | False
Column2 | Column2 | A | A | True

Copy row from datatable to another where there are common column headers

I have two datatables, I am trying to copy row from one table to another, I have tried this. the thing is that my tables are not exactly the same, both tables have common headers, but to the second table have more columns, therefore I need "smart" copy, i.e to copy the row according to the column header name.
d1:
+--------+--------+--------+
| ID | aaa | bbb |
+--------+--------+--------+
| 23 | value1 | value2 | <----copy this row
d2:
+--------+--------+--------+--------+
| ID | ccc | bbb | aaa |
+--------+--------+--------+--------+
| 23 | | value2 | value1 | <----I need this result
but this code:
string rowID=23;
DataRow[] result = dt1.Select($"ID = {rowID}");
dt2.Rows.Add(result[0].ItemArray);
gives:
d2:
+--------+--------+--------+--------+
| ID | ccc | bbb | aaa |
+--------+--------+--------+--------+
| 23 | value1 | value2 | | <---- :( NOT what I need
I think this is your homework, but here you have some simple and not very smart solution:
private DataTable DTCopySample()
{
int cnt = 0;
DataTable dt1 = new DataTable();
dt1.Columns.Add("ID");
dt1.Columns.Add("aaa");
dt1.Columns.Add("bbb");
DataTable dt2 = new DataTable();
dt2.Columns.Add("ID");
dt2.Columns.Add("ccc");
dt2.Columns.Add("bbb");
dt2.Columns.Add("aaa");
dt1.Rows.Add();
dt1.Rows[0]["ID"] = "23";
dt1.Rows[0]["aaa"] = "val1";
dt1.Rows[0]["bbb"] = "val2";
dt1.Rows.Add();
dt1.Rows[1]["ID"] = "99";
dt1.Rows[1]["aaa"] = "val99";
dt1.Rows[1]["bbb"] = "val98";
string colName = string.Empty;
foreach (DataRow row in dt1.Rows)
{
dt2.Rows.Add();
foreach (DataColumn col in dt1.Columns)
{
dt2.Rows[cnt][col.ColumnName] = row[col.ColumnName].ToString();
}
cnt++;
}
return dt2;
}
There are more smart and better solutions, but this is fast-written (2 mins) and works.
Remeber, that you have not specified columns datatypes or anything else, so I assumed there are strings everywhere for creating simple sample.

Load a specified column in DataGridView with values from a database

I have a database with a table. What I want to do is programatically load values from a column of the table to a column of the DataGridView.
I have a table "Actions", with a field "Total", which has some data: 10, 20, 35, 50, etc.
I want to put this field into the DataGridView in the 2nd column.
So the DataGridView should look like this.(the other columns are already set).
| Name | Total | Something |
|:-----------|------------:|:------------:|
| adsad | 10 | This |
| sddssdf | 20 | column |
| name1 | 35 | will |
| name | 50 | be |
| nmas | 1 | center |
| gjghjhh | 67 | aligned |
You need to create the particular column in Gridview and try following code :
DataGridView dataGridView2 = new DataGridView();
BindingSource bindingSource2 = new BindingSource();
dataGridView2.ColumnCount = 2;
dataGridView2.Columns[0].Name = "FieldOne";
dataGridView2.Columns[0].DataPropertyName = "FieldOne";
dataGridView2.Columns[1].Name = "FieldTwo";
dataGridView2.Columns[1].DataPropertyName = "FieldTwo";
bindingSource1.DataSource = GetDataTable();
dataGridView1.DataSource = bindingSource1;
you can add a new column to your DataTable and then bind it to your DataGridView.
//call SQL helper class to get initial data
DataTable dt = sql.ExecuteDataTable("sp_MyProc");
dt.Columns.Add("NewColumn", typeof(System.Int32));
foreach(DataRow row in dt.Rows)
{
//need to set value to NewColumn column
row["NewColumn"] = 0; // or set it to some other value
}
// possibly save your Dataset here, after setting all the new values
dataGridView1.DataSource = dt;

How to remove empty values in a DataTable rows and merge

I am trying to figure out a good way to remove empty values from rows and merge row2 to row1, row4 to row2 in a datatable.
DataTable with Empty rows to merge
---------------------
| Column1 | Column2 |
----------------------
ROW1 | XYZ | |
ROW2 | | ABC |
ROW3 | MNQ | |
ROW4 | | PQR |
Final datatable with merged rows
_____________________
| Column1 | Column2 |
----------------------
ROW1 | XYZ | ABC |
ROW2 | MNQ | PQR |
Can somebody help me accomplish this in C#?
Try to create two array that will store a column1 value and column2 value.
In loop go through all datatable rows and insert all not empty rows from column1 to array1 and rows from column2 to array2. Then on the end create new datatable that will have rows taked from array1 and array2.
For example in pseudocode.
var array1;
var array2;
for(var row in datatable)
{
if(row[column1] != null or empty)array1.push(row[column1].value);
if(row[column2] != null or empty)array2.push(row[column2].value);
}
and in the end (first check what array is biger).For example i assuming that array1 is bigger;
var newDatatable;
for(int i=0; i<array1.count; i++)
{
var row = new row;
newDatatable.row[column1].addRowValue(array1[i])
if(array2.count < i){
newDatatable.row[column2].addRowValue(array2[i])
}
}

C# - DataTable Link to GridView

I'm Working on a c# projet (webform).
Is it possible to Hide the name of the column when I Bind my DataTable to the Gridview ?
This is my DataTable:
¤----------¤----------¤----------¤
| Column 1 | Column 2 | Column 3 |
¤----------¤----------¤----------¤
| Data 1 | Data 1 | Data 1 |
¤----------¤----------¤----------¤
| Data 4 | Data 5 | Data 6 |
¤----------¤----------¤----------¤
and I would like to reach this in my GridView
¤----------¤----------¤----------¤
| Data 1 | Data 1 | Data 1 |
¤----------¤----------¤----------¤
| Data 4 | Data 5 | Data 6 |
¤----------¤----------¤----------¤
Is it possible and How could I do it please ?
EDIT:
In The First Row,I have many datas which are the same. How Could I join my cells in C# on my DataTable please?
¤----------¤----------¤----------¤----------¤----------¤----------¤
| Data 1 | Data 2 |
¤----------¤----------¤----------¤----------¤----------¤----------¤
| Data 4 | Data 5 | Data 6 | Data 7 | Data 8 | Data 9 |
¤----------¤----------¤----------¤----------¤----------¤----------¤
I would Like to reach this if possible
Have you tried setting the GridView's ColumnHeadersVisible property to False?
EDIT:
DataView view = new DataView(table);
DataTable distinctValues = view.ToTable(true, "Column1", "Column2" ...);
in web form
<asp:GridView runat="server" HeaderStyle-CssClass="hide">
</asp:GridView>
in css
.hide { display: none; }
DataRow dr = dt.Rows[0];
dr.Delete();
dt.AcceptChanges();
After that bind your datatable to your grid.
Edit
protected void OnDataBound(object sender, EventArgs e)
{
GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
TableHeaderCell cell = new TableHeaderCell();
cell.Text = "Your text1";
cell.ColumnSpan = 3;
row.Controls.Add(cell);
cell = new TableHeaderCell();
cell.ColumnSpan = 3;
cell.Text = "Your text2";
row.Controls.Add(cell);
GridView1.HeaderRow.Parent.Controls.AddAt(0, row);
}

Categories

Resources