need help to search MS Access Database C# - windows

i have created MS Access Database and it is working fine (ADD, DELETE, Update) now i need to use search function. i need to search using text box and a button.
i need to know how to search database using primary key and get those row values in to a text box or list box
I did it like this,
con.Open();
OleDbCommand cmd_ni = new OleDbCommand();
cmd_ni.Connection = con;
cmd_ni.CommandText = "SELECT * FROM Table1 WHERE vehicle_num = #vehicle_num";
cmd_ni.CommandType = CommandType.Text;
cmd_ni.Parameters.Add("id", OleDbType.VarChar);
cmd_ni.Parameters["id"].Value = nu_m;
OleDbDataReader dr1 = cmd_ni.ExecuteReader();
while (dr1.Read())
{
string ni;
ni = dr1["vehicle_num"].ToString();
if (nu_m == ni)
{
Class1.nn = ni;
DialogResult r = MessageBox.Show("the details");
if (r == DialogResult.OK)
{
//here i need the code to select the data row & show it in textbox.
}
}
}
dr1.Close();
con.Close();
after this point i cannot understand what to do. please help me....

Welcome to SO, You should try to google the answer first. But here are some resources that will help you on your way.
You should just add a textbox to your winform, and a button and on button click execute the code you show above. The only thing you need to add is a new parameter to your where statement.
This looks like a good walkthrough for you Youtube
and this SO answer looks at how to best structure it.
And after reading the answers look at related on the right hand side of the questions, There are many questions there that are looking in depth at this.

Related

How to use #JDBCDBColumn for typ ahead in xpages

Using Notes 9 and extension library's data controls...
I want to use the #JDBCDbColumn() to get the type ahead values from an Oracle table.
Is that possible at all? Does it work the same way the standard DBColumn in the type ahead?
Note that the DBColumn is looking in a huge table, but I specify a where clause that should filter what the JDBCDBColumn returns.
Somehow, nothing happens. Work sfine with Notes data though, but I need to get this working with the Oracle data.
Thanks!
Update 1: Code I have...
#JdbcExecuteQuery(
"oracle",
"select distinct postal_code from cifadmin.postal_codes where postal_code like '"
+ getComponent("CodePostal").getValue() + "%'")
Update 2: Here is the code I have right now, but it doesn't return anything:
var CodePostal = getComponent("rsSearchQuery").getValue();
if(!!CodePostal) {
var params = [CodePostal];
var a = #JdbcDbColumn("oracle", "postal_codes", "postal_code", "postal_code like ?", params);
return #Unique(a);
} else {
return "--";
}
OK, I got it working thanks to all your comments and a bit of intuition!!!
Here is the working code:
var sql = "SELECT DISTINCT POSTAL_CODE FROM cifadmin.POSTAL_CODES WHERE POSTAL_CODE LIKE'" + getComponent("PostalCode").getValue() +"%' ORDER BY POSTAL_CODE";
var res = #JdbcExecuteQuery("oracle", sql);
var values = new Array();
while (res.next()) {
values.push(res.getString("POSTAL_CODE"));
}
return values;
The thing that got it working was when I have forced 'values' as an array. Without that, it just doesn't work.
Picky and sensitive, XPages are!!!
Thanks to all for your help ;)
Just tested it the first time ever: works fine for me except I didn't use a WHERE clause in my sample and another type of DB here.
<xp:inputText id="inputText1" styleClass="form-control">
<xp:typeAhead mode="partial" minChars="1" ignoreCase="true">
<xp:this.valueList><![CDATA[#{javascript:#JdbcDbColumn("postgres", "xpagesdemo.names", "lastname")}]]></xp:this.valueList>
</xp:typeAhead>
</xp:inputText>
See live demo here: http://www.notesx.net/postgres.nsf/typeahead.xsp
Ben, I think you mean you want to put the wildcard to the end of the parameter? Not sure of your data and if you are entering an exact match? Did you try:
var params = [CodePostal+ "%"];
Also, not sure if you need to enter "cifadmin.postal_codes" for your table as you did in your sql?
Howard

Creating a DataTable in X++

I'm trying to create a datatable in microsoft ax x++.
I need to return some information back to a webservice. Problem is i'm having trouble getting this code to work. it runs to the point where i try to add a column because apparently that function doesn't work....
Does anyone have the code in full to create a datatable in x++. this code works up until the column code.. because basically what i'm doing is query some information and returning it back to a webservice.. unless theres another way to return multiple information back to a webservice that uses c#
System.Data.DataTable dt = new System.Data.DataTable("MyTable");
System.Data.DataColumnCollection columns = dt.get_Columns();
System.Data.DataColumn ProductName;
System.Data.DataColumn QtyOrdered;
System.Data.DataColumn ProductID;
System.Data.DataRow row;
ProductID = new System.Data.DataColumn("ProductID", System.Type::GetType("System.Int32"));
ProductName = new System.Data.DataColumn("ProductName", System.Type::GetType("System.String"));
QtyOrdered = new System.Data.DataColumn("QtyOrdered", System.Type::GetType("System.String"));
// dt.Columns.Add(ProductID);
// dt.Columns.Add(ProductName);
// dt.Columns.Add(QtyOrdered);
row=dt.NewRow();
Did you try replacing lines
// dt.Columns.Add(ProductID);
// dt.Columns.Add(ProductName);
// dt.Columns.Add(QtyOrdered);
with
columns.Add(ProductID);
columns.Add(ProductName);
columns.Add(QtyOrdered);
?
P.S. To populate the row:
System.Data.DataRowCollection rows = dt.get_Rows();
...
row = dt.NewRow();
row.set_Item("ProductID", 1);
row.set_Item("ProductName", "PN");
row.set_Item("QtyOrdered", "QO");
rows.Add(row);
I suggest you to read some MSDN articles such as .NET Interop from X++, How To Use X++ Syntax for CLR Arrays, etc. - it should help you understand how to use .NET assemblies from X++.

LinqToExcel - Need to start at a specific row

I'm using the LinqToExcel library. Working great so far, except that I need to start the query at a specific row. This is because the excel spreadsheet from the client uses some images and "header" information at the top of the excel file before the data actually starts.
The data itself will be simple to read and is fairly generic, I just need to know how to tell the ExcelQueryFactory to start at a specific row.
I am aware of the WorksheetRange<Company>("B3", "G10") option, but I don't want to specify an ending row, just where to start reading the file.
Using the latest v. of LinqToExcel with C#
I just tried this code and it seemed to work just fine:
var book = new LinqToExcel.ExcelQueryFactory(#"E:\Temporary\Book1.xlsx");
var query =
from row in book.WorksheetRange("A4", "B16384")
select new
{
Name = row["Name"].Cast<string>(),
Age = row["Age"].Cast<int>(),
};
I only got back the rows with data.
I suppose that you already solved this, but maybe for others - looks like you can use
var excel = new ExcelQueryFactory(path);
var allRows = excel.WorksheetNoHeader();
//start from 3rd row (zero-based indexing), length = allRows.Count() or computed range of rows you want
for (int i = 2; i < length; i++)
{
RowNoHeader row = allRows.ElementAtOrDefault(i);
//process the row - access columns as you want - also zero-based indexing
}
Not as simple as specifying some Range("B3", ...), but also the way.
Hope this helps at least somebody ;)
I had tried this, works fine for my scenario.
//get the sheets info
var faceWrksheet = excel.Worksheet(facemechSheetName);
// get the total rows count.
int _faceMechRows = faceWrksheet.Count();
// append with End Range.
var faceMechResult = excel.WorksheetRange<ExcelFaceMech>("A5", "AS" + _faceMechRows.ToString(), SheetName).
Where(i => i.WorkOrder != null).Select(x => x).ToList();
Have you tried WorksheetRange<Company>("B3", "G")
Unforunatly, at this moment and iteration in the LinqToExcel framework, there does not appear to be any way to do this.
To get around this we are requiring the client to have the data to be uploaded in it's own "sheet" within the excel document. The header row at the first row and the data under it. If they want any "meta data" they will need to include this in another sheet. Below is an example from the LinqToExcel documentation on how to query off a specific sheet.
var excel = new ExcelQueryFactory("excelFileName");
var oldCompanies = from c in repo.Worksheet<Company>("US Companies") //worksheet name = 'US Companies'
where c.LaunchDate < new DateTime(1900, 0, 0)
select c;

SQL Server Database is not updated via C# Code

I am performing record update operation . my update operation is happening fine but database is not updating values . below is update code.
SupPartEntityVal supplypart = new SupPartEntityVal();
String sNum = sNumText.Text;
String sName = sNameText.Text;
String sStatus = sText.Text;
String sCity = cText.Text;
int rowIndex = int.Parse(rIndex.Text);
ObjectQuery<S> supply = supplypart.S;
var query =
from product in supply
select new { product.SNUM, product.SNAME, product.STATUS, product.CITY };
S sup = supplypart.S.Single(product => product.SNUM == sNum);
sup.SNAME = sName; sup.STATUS = short.Parse(sStatus); sup.CITY = sCity;
this.supplypart.SaveChanges();
After making changes, I can see updated value on UI
After I close an application, reopen again I can see updated value on UI
Close Visual studio, reopen the application and run it again.
I do not see changes in database.
am i missing something???
You Can Check Your Record When Saving In Database through Select Query on Command.. And See That is record is Saving? If Yes.. Then Issue is in your Database ... Normally this occurs when we use OLEDB that is Storing Database in project,,,

Multiple rows update without select

An old question for Linq 2 Entities. I'm just asking it again, in case someone has came up with the solution.
I want to perform query that does this:
UPDATE dbo.Products WHERE Category = 1 SET Category = 5
And I want to do it with Entity Framework 4.3.1.
This is just an example, I have a tons of records I just want 1 column to change value, nothing else. Loading to DbContext with Where(...).Select(...), changing all elements, and then saving with SaveChanges() does not work well for me.
Should I stick with ExecuteCommand and send direct query as it is written above (of course make it reusable) or is there another nice way to do it from Linq 2 Entities / Fluent.
Thanks!
What you are describing isnt actually possible with Entity Framework. You have a few options,
You can write it as a string and execute it via EF with .ExecuteSqlCommand (on the context)
You can use something like Entity Framework Extended (however from what ive seen this doesnt have great performance)
You can update an entity without first fetching it from db like below
using (var context = new DBContext())
{
context.YourEntitySet.Attach(yourExistingEntity);
// Update fields
context.SaveChanges();
}
If you have set-based operations, then SQL is better suited than EF.
So, yes - in this case you should stick with ExecuteCommand.
I don't know if this suits you but you can try creating a stored procedure that will perform the update and then add that procedure to your model as a function import. Then you can perform the update in a single database call:
using(var dc = new YourDataContext())
{
dc.UpdateProductsCategory(1, 5);
}
where UpdateProductsCategory would be the name of the imported stored procedure.
Yes, ExecuteCommand() is definitely the way to do it without fetching all the rows' data and letting ChangeTracker sort it out. Just to provide an example:
Will result in all rows being fetched and an update performed for each row changed:
using (YourDBContext yourDB = new YourDBContext()) {
yourDB.Products.Where(p => p.Category = 1).ToList().ForEach(p => p.Category = 5);
yourDB.SaveChanges();
}
Just a single update:
using (YourDBContext yourDB = new YourDBContext()) {
var sql = "UPDATE dbo.Products WHERE Category = #oldcategory SET Category = #newcategory";
var oldcp = new SqlParameter { ParameterName = "oldcategory", DbType = DbType.Int32, Value = 1 };
var newcp = new SqlParameter { ParameterName = "newcategory", DbType = DbType.Int32, Value = 5 };
yourDB.Database.ExecuteSqlCommand(sql, oldcp, newcp);
}

Resources