How to bind two C# datatables to one ASP: GridView [duplicate] - c#

This question already has answers here:
Merging 2 datatables in to 1 datatable with same number of rows.
(3 answers)
Closed 5 years ago.
I have two datatables. I want to display them in one Asp: GridView side by side.
Dt1
Col1 co2
Dt2
Col3 col4
I want GridView to display as
Col1 col2 col3 col4
There is no relationship with those datatables.

My demo didn't check empty/null validation. If needed, please do.
//Create new class
public class FinalData
{
public string Col1 { get; set; }
public string Col2 { get; set; }
public string Col3 { get; set; }
public string Col4 { get; set; }
public FinalData(){}
}
//Populate your two tables into FinalData array as below
int MaxRows = dt1.Rows.Count > dt2.Rows.Count ? dt1.Rows.Count : dt2.Rows.Count;
FinalData[] fdList = new FinalData[MaxRows];
for (int i = 0; i < dt1.Rows.Count; i++)
{
FinalData[i] = new FinalData() { Col1 = dt1.Rows[i]["Col1"].ToString(), Col2 = dt1.Rows[i]["Col2"].ToString() };
}
for (int i = 0; i < dt2.Rows.Count; i++)
{
FinalData[i] = new FinalData() { Col3 = dt2.Rows[i]["Col3"].ToString(), Col4 = dt1.Rows[i]["Col4"].ToString() };
}
//Bind your gridview with fdList
YourGridview.DataSource = fdList;
YourGridView.DataBind();

You can use pivot table as follows this convert rows as columns
INSERT INTO #yourtable ([Id], [Value], [ColumnName])
VALUES
(1, 'John', 'FirstName'),
(2, '2.4', 'Amount'),
(3, 'ZH1E4A', 'PostalCode'),
(4, 'Fork', 'LastName'),
(5, '857685', 'AccountNumber');
SELECT
Firstname, Amount, PostalCode, LastName, AccountNumber
FROM
(SELECT
value, columnname
FROM
#yourtable) d
PIVOT
(MAX(value)
FOR columnname IN (Firstname, Amount, PostalCode, LastName, AccountNumber)
) piv;

Related

Inserting Scope identity into second table using Entity Framework and dynamic Json

I have two tables as follows
1) Customers
customerId Int (primary key)
customerName Varchar(50)
Age Int
2) CustomerLoan
Id Int
customerId Int (Foreign key)
customerName Varchar(50)
Age Int
Loan float
From my jquery I am getting multiple records in the form of dynamic json object in the webservice webmethod as shown below (InsertData).
By using IList and Entity framework I am inserting multiple records.
My requirement here is while inserting customers record, I want to inert few fields from customer table and extra fields in customerloan table.
Bottom line I want to insert cutomerId generated from customer table with few more fields in CustomerLoan table.
Ex:Customer
customerId customerName Age
100 John 32
101 Jacob 35
Ex: CustomerLoan
Id customerId customerName Age Loan
1 100 John 32 1500
2 101 Jacob 35 2000
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public dynamic InsertData(int revision, int appID, dynamic jsonMaster)
{
dynamic json = jsonMaster;
IList<Customer> customers = ((object[])json).Select(t => new Customer
{
customerId = Convert.ToInt32((((IDictionary)t)["customerId"]) ?? -1),
customerName = ((((IDictionary)t)["customerName"]) ?? "").ToString(),
Age = Convert.ToInt32(((IDictionary)t)["Age"]),
Revision = Convert.ToInt32((((IDictionary)t)["Revision"])),
}).ToList(); ;
lock (_updatePointsLock)
{
using (CustomerEntities context = new CustomerEntities())
{
int currentRevision = context.Customer.Max(x => x.Revision) ?? 0;
if (currentRevision >= revision)
{
foreach (Customer cobj in customers)
{
Customer obj = context.Customer.Where(x => x.customerId == cobj.salesMasterId).FirstOrDefault();
if (obj == null)
{
cobj.Revision = currentRevision + 1;
context.Customer.Add(cobj);
**CustomerLoan objLoan = new CustomerLoan();
objLoan.customerId = cobj.customerId;
objLoan.customerName = cobj.customerName;
objLoan.Age = cobj.Age;
objLoan.customerLoan = 1500;
context.CustomerLoan.Add(objLoan);**
}
else
{
obj.customerName = cobj.customerName;
obj.Age = cobj.Age;
obj.Revision = currentRevision + 1;
}
}
context.SaveChanges();
return new
{
Revision = currentRevision + 1,
Customer = context.Customer.Where(x => x.Revision > revision).Select(x => new
{
x.customerId,
x.customerName,
x.Age,
Revision = x.Revision,
}).ToList()
};
}
else
{
return new { Revision = revision };
}
}
}
}
With the above code (-1) value inserting in customerId field in customerLoan table.
If create objects to insert outside the foreach values of Customers not getting.
If someone can help inserting identity value customer table in customerLoan highly appreciated.
First save your customer object to database with context.SaveChanges();
Then try to add Customer loan (now you should be able to find the customer Id) and save again to database with context.SaveChanges();
It may have other ways to do it but this is the way I know.

How to loop and update SQL table summing any existing values

Please i need your help on this module part of my program. i have 2 tables, TableA which has "code,description,value" and TableB which has "code, values" example below :
TableA
code description value
-----------------------------
CD1 BOOKS
CD2 BREADS
CD3 PHONES
CD4 FISH
TableB
code value1 value2 value3 value4
--------------------------------------
cd1 12 21 10 21
cd2 9 10 10 11
cd3 19 11 29 13
cd4 10 12 22 12
the idea is to update TableA with the Values of TableB where TableA.code=TableB.code but if their are values in TableA then Update content of TableA Value field by adding the new values to the old value field where TableB.code = TableA.code. i have written the following code but it's only updating one row, below is my code :
DataTable dt = GetDatafromDatabase(); //===== returns a DataTable
string SQLT = "SELECT * FROM tbl_TempReport";
if (cn.State == ConnectionState.Closed) {cn.Open(); }
SqlCommand cmdT = new SqlCommand(SQLT, cn);
while (rt.Read())
{
// For each row, print the values of each column.
foreach (DataColumn column in dt.Columns)
{
foreach (DataRow row in dt.Rows)
{
colname = column.ColumnName.ToString();
string m_Code = rt["code"].ToString();
if (m_Code == colname) {
if (m_Code == colname && mValue > 0) { mValue += Convert.ToInt32(row[column].ToString()); } else { mValue = Convert.ToInt32(row[column].ToString()); }
//============ insert into tbl_TempReport to match the appropriate column
string SQLP = "UPDATE tbl_TempReport SET VALUEP = #VALUEP WHERE code = #code";
SqlCommand cmdp = new SqlCommand(SQLP, cn);
cmdp.Parameters.AddWithValue("#VALUEP", SqlDbType.Int).Value = mValue;
cmdp.Parameters.AddWithValue("#code", SqlDbType.NVarChar).Value = rt["code"].ToString();
cmdp.ExecuteNonQuery();
}
}
}
}
i need your help to achieve this. Thank you
If I understand the question, this can be done in a single update statement, without any loops:
UPDATE a
SET value = b.value1 + b.value2 + b.value3 + b.value4 + COALESCE(value, 0)
FROM TableA a
INNER JOIN TableB b ON(a.code = b.code)

Datatable Group by and sum one column

I have this datatable:
RadkyData.Columns.Add("ČísloDokladuDodavatele", typeof(string));
RadkyData.Columns.Add("Množství", typeof(string));
RadkyData.Columns.Add("NákupníCena", typeof(string));
RadkyData.Columns.Add("PřepočtováJednotka", typeof(string));
RadkyData.Columns.Add("Přepočtovýkoeficient",
Just group the rows by Col1, Col2,Col3 and Sum() up Col4
var input = new[] {
new { Col1 =1, Col2= 2, Col3 = 1, Col4 = 1.5m},
new { Col1 =1, Col2= 1, Col3 = 1, Col4 = 1.8m},
new { Col1 =1, Col2= 2, Col3 = 1, Col4 = 2.5m},
new { Col1 =1, Col2 =1, Col3 = 1, Col4 = 3m},
new { Col1 =3, Col2 =1, Col3 = 4, Col4= 5m}
};
var result = input.GroupBy(x => new { x.Col1, x.Col2, x.Col3 })
.Select(x => new
{
Col1 = x.Key.Col1,
Col2 = x.Key.Col2,
Col3 = x.Key.Col3,
Col4 = x.Sum(y => y.Col4)
});
You could do this using Linq.
table.AsEnumerable()
.Select(r=>new
{
c1=r.Field<int>("col1"),
c2 =r.Field<int>("col2"),
c3 =r.Field<int>("col3"),
c4 =r.Field<double>("col4")
})
.GroupBy(g=> new {g.c1, g.c2, g.c3})
.Select(x=> new {
col1 = x.Key.c1,
col2 = x.Key.c2,
col3 = x.Key.c3,
Sum = x.Sum(s=>s.c4)
});
Check this Demo
Output:
{ col1 = 1, col2 = 2, col3 = 1, Sum = 4 }
{ col1 = 1, col2 = 1, col3 = 1, Sum = 4.8 }
{ col1 = 3, col2 = 1, col3 = 4, Sum = 5 }
I think this should work
mytable.Columns.Add("col4",GetType(Integer),"Col1+Col2+Col3");

SELECT all columns in addition to some summary columns using LINQ

Suppose there is a table with more than 20 columns: (col1, col2, ... )
If I want to display the sum of col1 and col2 as well as the other columns,
In SQL I could:
SELECT (col1+col2), * FROM table1;
But in LINQ, I have to
from tb in table1
select new
{
sum = tb.col1 + tb.col2,
col1 = tb.col1,
col2 = tb.col2,
...
};
Is there another simpler ways? Thanks.
You can extend type of tb entity by sum property and write something like:
table1
.Select(tb => new
{
Tb = tb,
Sum = tb.col1 + tb.col2
})
.Select(x =>
{
x.Tb.sum = x.Sum;
return x.Tb;
});

How to concat a column value based on id

I have a table like this in C# from a dataset
COL1 COL2 COL3 COL4 COL5
1000 APPLE 50 92 TESTING
1000 APPLE 50 92 ALPHA
1000 APPLE 50 92 BETA
1000 APPLE 50 92 OMEGA
2000 ORANGE 60 90 DELTA
2000 ORANGE 60 90 TEST
2000 ORANGE 60 90 SLEEP
I need result like this
COL1 COL2 COL3 COL4 COL5
1000 APPLE 50 92 TESTINGAPHABETAOMEGA
2000 ORANGE 60 90 DELTASLEEPTEST
How to achieve this ?
I strucked after this line
var result = from row in dataTable.AsEnumerable()
group row by row.Field<int>("COL1") into grp
select new
{
COL1= grp.Key,
Count = grp.Count()
};
I dont think you can do that with LINQ, but heres a little subroutine that will work for you.
var _rowlist = table.AsEnumerable().OrderBy(x => x.Field<Int32>("COL1")).ThenBy(x => x.Field<string>("COL2")).ThenBy(x => x.Field<string>("COL3")).ThenBy(x => x.Field<string>("COL4")).ToList();
DataTable _newtable = table.Clone();
string oldrowid = "";
foreach (DataRow _indrow in _rowlist)
{
if (!oldrowid.Equals(_indrow["COL1"].ToString()))
{
oldrowid = _indrow["COL1"].ToString();
DataRow _newrow = _newtable.NewRow();
_newrow["COL1"] = _indrow["COL1"].ToString();
_newrow["COL2"] = _indrow["COL2"].ToString();
_newrow["COL3"] = _indrow["COL3"].ToString();
_newrow["COL4"] = _indrow["COL4"].ToString();
_newrow["COL5"] = _indrow["COL5"].ToString();
_newtable.Rows.Add(_newrow);
}
else
{
Int32 _id = Int32.Parse(_indrow["COL1"].ToString());
DataRow _row = _newtable.AsEnumerable().Where(a => a.Field<Int32>("COL1") == _id).SingleOrDefault();
int Index = _newtable.Rows.IndexOf(_row);
_row["COL5"] += "," + _indrow["COL5"].ToString();
}
}
//_newtable contains what you want
Try this:
var result =
from row in dataTable.AsEnumerable()
let COL1 = row.Field<int>("COL1")
let COL2 = row.Field<string>("COL2")
let COL3 = row.Field<int>("COL3")
let COL4 = row.Field<int>("COL4")
let COL5 = row.Field<string>("COL5")
group COL5 by new { COL1, COL2, COL3, COL4, } into grp
select new
{
COL1 = grp.Key.COL1,
COL2 = grp.Key.COL2,
COL3 = grp.Key.COL3,
COL4 = grp.Key.COL4,
COL5 = String.Join("", grp),
};
var result = from row in dt.AsEnumerable()
group row by row.Field<int>("COL1") into grp
let firstCols = grp.First()
let lastCells = string.Join("", grp.Select(x => x[4]).ToArray())
select new object[] { firstCols[0], firstCols[1], firstCols[2], firstCols[3], lastCells };
var dtResult = dt.Clone();
foreach (var item in result )
{
dtResult.Rows.Add(item);
}

Categories