How to sort DataSet by column [duplicate] - c#

This question already has answers here:
Sorting a Data Table
(5 answers)
Closed 4 years ago.
My SQL database was created in SQL Server Management Studio. I have a dataset table that works great, which was sorted by the primary key id column from an example I copied, which was fine when there were only a few entries. Now I want to sort by the Model_no column.
I have tried to sort the table like this:
ds.Tables[0].DefaultView.Sort = "Model_no";
and like this:
DataTable table = ds.Tables[0];
DataView view = table.DefaultView;
view.Sort = "Model_no";
But the table is still sorted by primaryKey.
objConnect = new DatabaseConnection();
conString = "Server=VENUS;" +
"Initial Catalog=TestRig;" +
"User id=TestRig;" +
"Password=act1ve;" +
"MultipleActiveResultSets = true;";
objConnect.connection_string = conString;
objConnect.Sql = Properties.Settings.Default.SQL;
ds = objConnect.GetConnection;
DataTable table = ds.Tables[0]; // Neither this
DataView view = table.DefaultView;
view.Sort = "Model_no";
// ds.Tables[0].DefaultView.Sort = "Model_no"; // or this work
// When I click next record, I inc the row, then get the datarow and
display in my form
inc++;
dRow = ds.Tables[0].Rows[inc];
dummy = dRow.ItemArray.GetValue(0).ToString(); // Primary Id
exVol = dRow.ItemArray.GetValue(1).ToString();
tbExcitationVoltage.Text = exVol.Trim();
When I open the form I expect the first entry to be sorted by the model number, but instead see record 1 (primary ID), how can I sort by another column please?

You need to read from DefaultView. If you need to read from the table you can do the following.
ds.Tables[0].DefaultView.Sort = "Model_no";
DataTable dt = ds.Tables[0].DefaultView.ToTable();

Related

Insert NON-DUPLICATE Data into SQL Database from Excel file using ASP.NET Core 3.1

I'm trying to use two C# DataTables like below to meet my requirement.
dtExcelData: This DataTable holds the data which is uploaded from Excel file. This data should be inserted into SQL Server Database based on certain conditions which were mentioned below.
dtDbData: This DataTable holds data from Database. Preparing this DataTable just by reading two columns which represent Primary Key.
I'm using dtExcelData datatable to save records into SQL Server Database after uploading Excel file.
The requirement is that I should validate dtExcelData before I insert into database. There exists 39 columns in dtExcelData datatable with the column headings column1, column2, ... column39. And, the number of rows can range upto 400 (or even little more).
I've to do validation like below:
column6, and column22 from Excel file combinedly is considered as primary key. If this same data is already available in database, I should NOT consider that record to insert into database. I can simply ignore that record. All other records should be inserted into database.
I've tried number of approaches to meet this requirement, but unable to arrive to proper solution.
I am looking for some approach like below:
dtExcelData.Except(dtDbData, SomeDataComparerForTheseTwoColumns)
Looking for some help.
Below is a work demo, you can refer to it.
DataTable dtExcelData = new DataTable();
dtExcelData.Columns.Add("Id", typeof(int));
dtExcelData.Columns.Add("Name", typeof(string));
DataRow row = dtExcelData.NewRow();
row["Id"] = 1;
row["Name"] = "John";
dtExcelData.Rows.Add(row);
DataRow row2 = dtExcelData.NewRow();
row2["Id"] = 2;
row2["Name"] = "Max";
dtExcelData.Rows.Add(row2);
DataRow row3= dtExcelData.NewRow();
row3["Id"] = 2;
row3["Name"] = "John";
dtExcelData.Rows.Add(row3);
DataRow row4 = dtExcelData.NewRow();
row4["Id"] = 1;
row4["Name"] = "Max";
dtExcelData.Rows.Add(row4);
DataRow row5 = dtExcelData.NewRow();
row5["Id"] = 3;
row5["Name"] = "Tom";
dtExcelData.Rows.Add(row5);
DataTable dtDbData = new DataTable();
dtDbData.Columns.Add("Id", typeof(int));
dtDbData.Columns.Add("Name", typeof(string));
DataRow rrow = dtDbData.NewRow();
rrow["Id"] = 1;
rrow["Name"] = "John";
dtDbData.Rows.Add(rrow);
DataRow rrow2 = dtDbData.NewRow();
rrow2["Id"] = 2;
rrow2["Name"] = "Max";
dtDbData.Rows.Add(rrow2);
//match up the column and then find the missing.
var matched = from r1 in dtExcelData.AsEnumerable()
join r2 in dtDbData.AsEnumerable()
on r1.Field<int>(0) equals r2.Field<int>(0)
where r1.Field<string>(1) == r2.Field<string>(1)
select r1;
//This should give you the rows which do not have a match
var missing = from table1 in dtExcelData.AsEnumerable()
where !matched.Contains(table1)
select table1;
if (missing.Any())
{
//use for/foreach loop through each row and then insert into database.
// do something with these rows
}
result:

Update a set of rows of a table having no primary key

I want to update set of rows using ODP.net.
I want to get list of employees based on increasing asscending order of PRIORITY and update PRIORITY column with value 1 and increment by 1.
I tried below approach and it gives error "Dynamic SQL generation failed. No key information found"
StrQuery = "SELECT * FROM EMPLOYEE WHERE DEPT ='" + dept + "' ORDER BY PRIORITY";
DataTable dt = new DataTable();
OracleDataAdapter da = new OracleDataAdapter();
da.SelectCommand = new OracleCommand(StrQuery, ora);
OracleCommandBuilder cb = new OracleCommandBuilder(da);
da.Fill(dt);
intNpriority = 1;
foreach (DataRow row in dt.Rows)
{
row["PRIORITY"] = intNpriority;
intNpriority = intNpriority + 1;
}
da.UpdateCommand = cb.GetUpdateCommand();
da.Update(dt);
The table has no primary key and i cannot add one now. Can i add custom update query and how? Is there anyalternative way to acheive same?
table strucure:
column name | (data type)
Employee_name | (varchar2)
dept | (varchar2)
PRIORITY | (NUMBER)
I've spent two days to find some way to workaround.
Lucky that I could get it done.
The idea is to add a dump primary key in the DataTable, this new dump column does not affect the real database table.
Here's my code sample
Dim currentRow = m_DataTable.Rows(m_RowPosition)
Dim tmpRows() As DataRow = {currentRow}
Dim cmdBuilder As OracleCommandBuilder = New OracleCommandBuilder(m_Adapter)
**If m_DataTable.PrimaryKey.Count = 0 Then
m_DataTable.Columns.Add(New DataColumn("_ID_", System.Type.GetType("System.String")))
m_DataTable.Columns("_ID_").Unique = True
End If**
m_Adapter.Update(tmpRows)
Note: The currentRow is the row is being edited .
Please consider carefully to apply this tip because it might update all data of table.
It's suitable for case your table has only one row ( some kind of configuration data )

Getting columns from DataTable stored in session

So I have a DataTable which uses:
SELECT * FROM People WHERE ID = ?
You can understand that this will only retrieve one row as the ID is unique:
usersTableAdapters.UsersTableAdapter user = new usersTableAdapters.UsersTableAdapter();
users.UsersDataTable userDataTable = user.getUserInfo(id);
I have then stored the DataTable into a session:
HttpContext.Current.Session.Add("userDT", userDataTable);
Now I am trying to figure out, how would I get a specific column from the userDT in the session? To be more clear the firstname column?
First cast the session object as a datatable.
var tbl = ((DataTable)HttpContext.Current.Session["userDT"])
Then use it like a data table:
var col = tbl.Columns["firstName"];
You have to cast Session object to users.UsersDataTable:
users.UsersDataTable userDataTable = Session["userDT"] as users.UsersDataTable;
Try this,
DataView dv = new DataView((DataTable)HttpContext.Current.Session["userDT"]);
get the table just with column
DataTable dt = dv.ToTable(true, "firstName");

Cannot retrieve data from database in C#

I have an application,which is not able to fetch data from the database for this specific form, while other forms are working fine.
I am using this form to fetch data from database and then display that data onto labels on an another form.
The code for fetching data is:
string PName, DName, Psex, PPhoneNo, PAddress, Treatment, Teethno, PAge, Amount;
SqlDataAdapter a = new SqlDataAdapter("Select bills.BillNo,bills.PName,bills.DName,bills.PAge,bills.PSex,bills.PPhoneNo,bills.PAddress,bills.Treatment,bills.Amount,bills.Teethno,addpro.Medicines from bills,addpro where bills.BillNo=" + bno, Program.con);
DataTable t = new DataTable();
a.Fill(t);
PAge = Convert.ToString(t.Rows[3]);
Amount = Convert.ToString(t.Rows[8]);
PName = Convert.ToString(t.Rows[1]);
DName = Convert.ToString(t.Rows[2]);
Psex = Convert.ToString(t.Rows[4]);
PPhoneNo = Convert.ToString(t.Rows[5]);
PAddress = Convert.ToString(t.Rows[6]);
Treatment = Convert.ToString(t.Rows[7]);
Teethno = Convert.ToString(t.Rows[9]);
frmPrint sa=new frmPrint();
sa.start(bno, PAge, Amount, PName, DName, Psex, PPhoneNo, PAddress, Treatment, Teethno);
when i try to load the next form which displays the data from this DataTable on labels it gives the following error:-
There is no row at position 3.
Your're using Row and you want to be using Column:
foreach(DataRow row in t.Rows)
{
PAge = row["PAge"].ToString();
Amount = row["Amount"].ToString();
PName = row["PName"].ToString();
DName = row["DName"].ToString();
Psex = row["PSex"].ToString();
PPhoneNo = row["PPhoneNo"].ToString();
PAddress = row["PAddress"].ToString();
Treatment = row["Treatment"].ToString();
Teethno = row["Teethno"].ToString();
}
Instead of using the number to identify the column, use the name. If the order of the query was to change for any reason, this would not have an impact on your code. If you used the Ordinal number, then you would need to change your row[n] code too since the order would have changed.
You are accessing different rows for each field.
You should access the first row and then different columns:
t.Rows[0].Columns[0]
t.Rows[0].Columns[1]
t.Rows[0].Columns[2]
t.Rows[0].Columns[3]
...
Seems like you need to use [Columns]
DataTable t = new DataTable();
a.Fill(t);
PAge = Convert.ToString(t.Rows[0]["ColumnsName"]);
// and so on

How to Get a Column number in Excel by its Column name

I created an Excel application using C# with MVVM model. In that excel file I created some columns as template columns. For example I am having some columns like Unit, Cost and Quantity. Now I want to find the exact column number of "Quantity" .
How can I get that particular column(Quantity) number?
Please can any one tell me some method to achieve this?
Execute the Select statement and fill the dataset. Now traverse through the column in the table and find the index of column 'Quantity".
Sample code to load the excel file in Dataset:
public static DataSet exceldata(string filelocation)
{
DataSet ds = new DataSet();
OleDbCommand excelCommand = new OleDbCommand(); OleDbDataAdapter excelDataAdapter = new OleDbDataAdapter();
string excelConnStr = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + filelocation + "; Extended Properties =Excel 8.0;Hdr=Yes";
OleDbConnection excelConn = new OleDbConnection(excelConnStr);
excelConn.Open();
DataTable dtPatterns = new DataTable(); excelCommand = new OleDbCommand("SELECT `PATTERN` as PATTERN, `PLAN` as PLAN FROM [PATTERNS$] where 1=0", excelConn);
excelDataAdapter.SelectCommand = excelCommand;
excelDataAdapter.Fill(dtPatterns);
"dtPatterns.TableName = Patterns";
ds.Tables.Add(dtPatterns);
return ds;
}
By using this method, you have loaded the table schema in dataset. Now you can store the column name and index in any of the collection variable and get the column index using the key column name in that collection.

Categories

Resources