litedb see results from query - c#

I would like to know how to see the results from a database in text format from LiteDB in the console or a multi line text box when the form loads. This is what I have so far, but it doesn't return the information.
private void DisplayData_Load(object sender, EventArgs e)
{
using (var db = new LiteDatabase(#"C:\Temp\MyData.db"))
{
// Get a collection (or create, if doesn't exist)
var col = db.GetCollection<DataBase>("data");
// Create your new customer instance
var results = col.FindAll();
Console.WriteLine(results);
}
}

I think I found a version of the answer. This code displays the data to a combo box, console output, or as text for a text box...
public class DataBase
{
[BsonId]
public string GetSetVariable { get; set; }
}
private void DisplayData_Load(object sender, EventArgs e)
{
using (var db = new LiteDatabase(#"C:\Temp\MyData.db"))
{
// Get a collection (or create, if doesn't exist)
var col = db.GetCollection<DataBase>("collection_name");
// Enter data into the database
var incomingData = new Database
{
GetSetvariable = "This is output text."
};
// Create unique index in Name field
col.EnsureIndex(x => x.GetSetVariable, true);
// Insert new customer document (Id will be auto-incremented)
col.Insert(incomingData);
// Update a document inside a collection
incomingData.GetSetVariable = "Updated Text Record";
col.Update(incomingData);
// Create a query
var results = col.FindAll();
// To display ALL columns of 'results' in a combo box.
foreach (var finding in results)
{
var variable = finding.GetSetVariable;
comboBox1.Items.Add(variable);
Console.WriteLine(variable);
}
// To display one record of 'results' to a text box.
var query = col.FindById(1);
var variable = query.GetSetVariable;
textBox1.Text = variable;
Console.WriteLine(variable);
}
}

Related

How to fetch data to ComboBox from a Linq query?

I wanted get set of data and append to combobox from database using linq.
I have did it already but when i save data. My db saved value looks like this:
{
schid = 1004,
schoolname = St John Bossco
}
I only wanted to save the string value of the school name. how can i approach that?
This is my code:
private void get_combo_vale_list()
{
using (DBEntity db = new DBEntity())
{
var school = db.basicdata_school.Select(x => new { x.schid, x.schoolname });
cmbalschool.DataSource = school.ToList();
cmbalschool.ValueMember = "schid";
cmbalschool.DisplayMember = "schoolname";
cmbalschool.SelectedItem = null
}
}

Pull full dynamodb table with document model

string tableName = _awsSettings.TableSettings.Table + _awsSettings.TableSettings.Suffix;
Table table = Table.LoadTable(_amazonDynamoDb, tableName);
DocumentBatchGet batch = table.CreateBatchGet();
await batch.ExecuteAsync();
List<Document> results = batch.Results;
return results.As<Lab>();
The above code returns 0 results. I am hoping to return the entire table.
How can I, using the document model (Table.LoadTable), pull the entire table?
The Table.LoadTable() method returns a Table object, which is basically a wrapper for the DynamoDB client. This object does not contain any of the data that is in the actual table in AWS.
To read all of the items in a table, you need to use the Table.Scan() method. Here is some sample code that uses scan to dump the contents of a table to the standard output.
private static void DumpTable(Table table)
{
ScanFilter scanFilter = new ScanFilter();
Search search = productCatalogTable.Scan(scanFilter);
List<Document> documentList = new List<Document>();
do
{
documentList = search.GetNextSet();
foreach (var document in documentList)
PrintDocument(document);
} while (!search.IsDone);
}
private static void PrintDocument(Document document)
{
// count++;
Console.WriteLine();
foreach (var attribute in document.GetAttributeNames())
{
string stringValue = null;
var value = document[attribute];
if (value is Primitive)
stringValue = value.AsPrimitive().Value.ToString();
else if (value is PrimitiveList)
stringValue = string.Join(",", (from primitive
in value.AsPrimitiveList().Entries
select primitive.Value).ToArray());
Console.WriteLine("{0} - {1}", attribute, stringValue);
}
}
This C# code is to pull records from a dynamodb table having different guid's using BatchGet or CreateBatchGet
string tablename = "AnyTableName"; //table whose data you want to fetch
var BatchRead = ABCContext.Context.CreateBatchGet<ABCTable>(
new DynamoDBOperationConfig
{
OverrideTableName = tablename;
});
foreach(string Id in IdList) // in case you are taking string from input
{
Guid objGuid = Guid.Parse(Id); //parsing string to guid
BatchRead.AddKey(objGuid);
}
await BatchRead.ExecuteAsync();
var result = BatchRead.Results;
// ABCTable is the table modal which is used to create in dynamodb & data you want to fetch

DataBind into DB from Class in asp.net

I'm filling up a database from an aspx web application.
Everything works fine, except for the fact that I use multiple pages for users to fill in their data into DB.
So, i got this method in one class.cs file:
public class Botones
{
public void SaveCVInfo2(string varOne,string varTwo, string varThree)
{
using (ConexionGeneralDataContext db = new ConexionGeneralDataContext())
{
Usuario_Web columna = new Usuario_Web();
//Add new values to each fields
columna.Nombre = varOne;
columna.Apellido = varTwo;
columna.Em_solicitado = varThree;
//and the rest where the textboxes would have been
//Insert the new Customer object
db.Usuario_Web.InsertOnSubmit(columna);
//Sumbit changes to the database
db.SubmitChanges();
}
}
}
This is just a part of the file, it has more columns, but it doesn't change the example.
However, I added another class.cs file in order to reference it's method from a button in the second page. Just like the one I posted before in this post:
public class Botones2
{
public void SaveCVInfo3(string varOne, string varTwo, string varThree, string varFour, string varFive, string varSix, string varSeven,
string varEight, string varNine, string varTen, string varEleven, string varTwelve, string varThirteen, string varFourteen, string varFifteen)
{
using (ConexionGeneralDataContext db = new ConexionGeneralDataContext())
{
Usuario_Web columna = new Usuario_Web();
//Insert the new Customer object
columna.Estatus = 1;
columna.nombre_esposo = varOne;
columna.profe_compa = varTwo;
columna.emp_compa = varThree;
columna.cargo_actual_compa = varFour;
columna.Hijos = varFive;
columna.Edades_hijos = varSix;
columna.persona_depende_compa = varSeven;
columna.afinidades = varEight;
columna.Edades_depende = varNine;
columna.nom_padre = varTen;
columna.profesion_padre = varEleven;
columna.tel_padre = varTwelve;
columna.nom_madre = varThirteen;
columna.profesion_madre = varFourteen;
columna.tel_madre = varFifteen;
db.Usuario_Web.InsertOnSubmit(columna);
//Sumbit changes to the database
db.SubmitChanges();
}
}
}
AS you can see there are more columns I'm filling into the db, in the same table, problem is, when i submit data to the sql server, from second page, it just creates a new Usuario_web without the columns i referenced in first class.
What i need is to bind somehow the data already sent from first page. So first class is associated with all other classes, and columns are filled in the same row.
If anybody knows how to handle this situation, please let me know.
EDIT
This is how i call methods from asp buttons:
protected void Button1_Click(object sender, EventArgs e)
{
Botones botones = new Botones();
botones.SaveCVInfo2(nombre.Text, Apellidos.Text, EmpleoS.Text);
}
And SaveCVInfo3:
protected void Button1_Click(object sender, EventArgs e)
{
Botones2 botones2 = new Botones2();
botones2.SaveCVInfo3(nombre_compa.Text, Profesion_compa.Text, Emp_trabaja.Text, Cargo_compa.Text, RadioButtonList8.SelectedItem.Text, edades_sons.Text, num_depende.Text, Afinidad.Text, Edad_compa.Text, nom_padre.Text, profesion_compa_padre.Text, Tel_compa.Text, nom_madre.Text, profesion_compa_madre.Text, Tel_compa_madre.Text);
Response.Redirect("Envia3.aspx");
}
CAUTION: Untested code below.
I would return the columna.ID from SaveCVInfo2:
public int SaveCVInfo2(string varOne,string varTwo, string varThree)
{
int columnaId = 0;
using (ConexionGeneralDataContext db = new ConexionGeneralDataContext())
{
Usuario_Web columna = new Usuario_Web();
//Add new values to each fields
columna.Nombre = varOne;
columna.Apellido = varTwo;
columna.Em_solicitado = varThree;
//and the rest where the textboxes would have been
//Insert the new Customer object
db.Usuario_Web.InsertOnSubmit(columna);
//Sumbit changes to the database
db.SubmitChanges();
columnaId = columna.ID;
}
return columnaId;
}
And call the method, get the ID and save in the Session like this:
protected void Button1_Click(object sender, EventArgs e)
{
int columnaId = 0;
Botones botones = new Botones();
columnaId = botones.SaveCVInfo2(nombre.Text, Apellidos.Text, EmpleoS.Text);
Session["columnaId"] = columnaId.ToString();
}
Now when calling the SaveCVInfo3 method, I can pass the columnaId:
protected void Button1_Click(object sender, EventArgs e)
{
int columnaId = 0;
if(Session["columnaId"] != null && int.TryParse(Session["columnaId"].ToString(), out columnaId)
{
Botones2 botones2 = new Botones2();
botones2.SaveCVInfo3(columnaId, nombre_compa.Text, Profesion_compa.Text, Emp_trabaja.Text, Cargo_compa.Text, RadioButtonList8.SelectedItem.Text, edades_sons.Text, num_depende.Text, Afinidad.Text, Edad_compa.Text, nom_padre.Text, profesion_compa_padre.Text, Tel_compa.Text, nom_madre.Text, profesion_compa_madre.Text, Tel_compa_madre.Text);
Response.Redirect("Envia3.aspx");
}
}
And in SaveCVInfo3 method I would get the object by Id, which is already saved in previous page and edit it, save it:
public void SaveCVInfo3(int columnaId, string varOne, string varTwo, string varThree, string varFour, string varFive, string varSix, string varSeven,
string varEight, string varNine, string varTen, string varEleven, string varTwelve, string varThirteen, string varFourteen, string varFifteen)
{
using (ConexionGeneralDataContext db = new ConexionGeneralDataContext())
{
//You will need to add reference to Linq if not added already
//Usuario_Web columna = new Usuario_Web();
//Insert the new Customer object
Usuario_Web columna = (Usuario_Web)db.Usuario_Webs.Find(columnaId);
columna.Estatus = 1;
columna.nombre_esposo = varOne;
columna.profe_compa = varTwo;
columna.emp_compa = varThree;
columna.cargo_actual_compa = varFour;
columna.Hijos = varFive;
columna.Edades_hijos = varSix;
columna.persona_depende_compa = varSeven;
columna.afinidades = varEight;
columna.Edades_depende = varNine;
columna.nom_padre = varTen;
columna.profesion_padre = varEleven;
columna.tel_padre = varTwelve;
columna.nom_madre = varThirteen;
columna.profesion_madre = varFourteen;
columna.tel_madre = varFifteen;
//db.Usuario_Web.InsertOnSubmit(columna);
//Sumbit changes to the database
db.SubmitChanges();
}
}
EDIT If Id is not a primary key, you can change this part-
Usuario_Web columna = (Usuario_Web)db.Usuario_Webs.Find(columnaId);
to :
Usuario_Web columna =(Usuario_Web)db.Usuario_Web.Where(x=>x.ID == columnaId).FirstOrDefault()

How do we assign individual lists as gridview columns?

I have performed enormous amount of Google search on this topic but couldn't really find the proper answer to this question. The solution might be simple, but I am a beginner to C# ASP.NET.
I have some code that is taking and storing user inputs from a dropdown list and a textbox into its individual List. I am trying to display both lists in a single gridview as individual columns. For an example, when a user selects a product and type in the quantity and hits the add button, it should display the details in a single row of a gridview. Now I have achieved saving the data into a list but cannot get it to display it in a single row.
Here is my code:
List<string> productIdList = new List<string>();
List<string> productTemp = new List<string>();
List<string> quantityList = new List<string>();
List<string> quantityTemp = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
productTemp = (List<string>)ViewState["productId"];
quantityTemp = (List<string>)ViewState["quantity"];
string str1 = Convert.ToString(productTemp);
string str2 = Convert.ToString(quantityTemp);
if (str1 != "")
{
if (productTemp.Count != 0)
{
foreach (string ids in productTemp)
{
productIdList.Add(ids);
}
}
}
if (str2 != "")
{
if (quantityTemp.Count != 0)
{
foreach (string qtys in quantityTemp)
{
quantityList.Add(qtys);
}
}
}
}
}
protected void btnContinue_Click(object sender, EventArgs e)
{
productIdList.Add(ddlProduct.SelectedValue.ToString());
quantityList.Add(txtQuantity.Text);
ViewState["productId"] = productIdList;
ViewState["quantity"] = quantityList;
txtQuantity.Text = "";
ArrayList testList = new ArrayList();
testList.AddRange(productIdList);
testList.AddRange(quantityList);
grdTest.DataSource = testList;
grdTest.DataBind();
grdProduct.DataSource = productIdList;
grdProduct.DataBind();
grdQuantity.DataSource = quantityList;
grdQuantity.DataBind();
}
}
The gridview currently present are for test purpose to check if data persists after every click of button. grdTest is what I am using for trying to display my list as columns.
Final would be something like this:
Name Qty
----- -----
Name1(list1) 5(list2)
Thanks!
You can use Linq to create List of object with Name and Qty from two lists like below
var temp = productIdList.Zip(quantityList, (n, w) => new { Name = n, Qty = w });
grdTest.DataSource = temp.ToList();
grdTest.DataBind();
Gridview you have to show both name and quantity in one row, if you join name and quantity to a one list it will not display as you expected ( all will show in one column)
we can create new class with Name and Qty as properties and create List of items by iterating though productIdList and quantityList.
Read more about Enumerable.Zip

Comparing Arrays and Create data into database

I'm now stuck regarding array comparison and creating it. I have 2 tables, station and location. The columns inside station is the id and the station name. there goes the same to the location table only different is the name. I put the id into a array and the name to the array. I wanted to compare the name and the id so that when user select the name, the program knows which id belongs to the selected name and save it into the other table using their primary keys. Here were the codes that I created from now but I don't know how to solve it. Hope I could get some help here. Thanks!
private void btnCreate_Click(object sender, EventArgs e)
{
using (testEntities Setupctx = new testEntities())
{
string[] stations = StationNameList();
int[] stationsID = StationIDList();
string[] locations = LocationNameList();
int[] locationsID = LocationIDList();
int Stationindex = cbStation.SelectedIndex;
int Locationindex = cbLocation.SelectedIndex;
trolleyservice TS = new trolleyservice();
TS.stationID = cbStation.SelectedIndex;
TS.locationID = cbLocation.SelectedIndex;
TS.tServiceTiming = txtTime.Text;
TS.tServiceType = txtType.Text;
Setupctx.trolleyservices.AddObject(TS);
txtTime.Text = "";
txtType.Text = "";
MessageBox.Show("New Trolley Service Has Been Created.");
}
}
Here were all the arrays that I created for each tables.
private string[] StationNameList()
{
using (testEntities Setupctx = new testEntities())
{
return Setupctx.stations.Select(s => s.Station1).OrderBy(s => s).ToArray();
}
}
private int[] StationIDList()
{
using (testEntities Setupctx = new testEntities())
{
return Setupctx.stations.Select(sid => sid.idstations).OrderBy(sid => sid).ToArray();
}
}
private string[] LocationNameList()
{
using (testEntities Setupctx = new testEntities())
{
return Setupctx.locations.Select(l => l.Location1).OrderBy(l => l).ToArray();
}
}
private int[] LocationIDList()
{
using (testEntities Setupctx = new testEntities())
{
return Setupctx.locations.Select(lid => lid.idlocation).OrderBy(lid => lid).ToArray();
}
}
Here you can do thing, instead of taking two different array of name and id you can take list of station class like this.
private List<stations> StationNameList()
{
using (testEntities Setupctx = new testEntities())
{
return Setupctx.stations.OrderBy(s => s.Station1).ToList();
}
}
now assign this list to cbStation as datasource like this
cbStation.DataSource =StationNameList() ;
cbStation.DataTextField = "Station1";//it is text field that you want to display
cbStation.DataValueField = "idstations";//it is value field of combo box
cbStation.DataBind();
Now use SelectedValue property of conbobox instead of SelectedIndex property you will get
station id that related to station name.
TS.stationID = cbStation.SelectedValue;
Same thing is for location also
you can also use array instead list here.

Categories

Resources