I am fairly new to this, and am having some issues trying to set a Picker SelectedItem to an existing SQLite table.
I have managed to populate the picker (and tables) with no issues. Now I need to Updated (or Insert) the existing cell value with the SelectedItem.
I can set the SelectedItem value, but when trying to insert it into an existing table I am having issues.
I did find one way to get it set, but doing so creates a new table each time (with the SelectedItem correctly displaying).
Is there something I am missing to get the SelectedItem into an existing table, without having to create a new table each time?
Thanks!
Xaml.cs
void TermGoClicked(object sender, EventArgs e)
{
//local database where populated table is stored
using (SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation))
{
//sets the Picker SelectedItem index
var pickerItem = termPicker.Items[termPicker.SelectedIndex];
//created new Courses table
var courses = new Courses();
//sets the PickerItem column with the Selected Item on newly created table.
courses.PickerItem = pickerItem;
conn.Update(courses);
Navigation.PushAsync(new TermPage());
}
}
Xaml
<Picker x:Name="termPicker"
ItemsSource="{Binding terms}"
ItemDisplayBinding="{Binding TermName}"
Title="Select a term"
IsEnabled="True"/>
I got it!
I had tried to access the existing Courses table using
var courses = conn.Table<Courses>;
but it wouldn't find the PickerItem column. So I had removed it. However, I added
var courses = conn.Table<Courses>.FirstOrDefault();
And it worked perfectly!
Thanks #Jason for pointing me in the right direction!
Related
First and foremost, I'm pretty new to programming, so attention to detail is appreciated.
I've currently got an asp checkbox list that receives data from an SQL table. I'm encountering a problem where if there's 2 items that are exactly the same, my remove function will remove both items. The following is the code for that:
protected void btn_remove_Click(object sender, EventArgs e)
{
for (int i = 0; i < UPCList.Items.Count; i++)
{
if (UPCList.Items[i].Selected)
{
var item = UPCList.Items[i];
var frcID = item.Value;
_itemNumberRepository.Delete(frcID);
}
}
Response.Redirect("WebForm2.aspx");
Response.End();
}
public string Delete(string itemCode)
{
string connectionString = foobar
Int32 returnDeleted = 0;
string deleteUpcCode =
"DELETE FROM compare1 "
+ string.Format("WHERE itemcode = '{0}'",itemCode);
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(deleteUpcCode, connection);
command.Connection.Open();
returnDeleted = command.ExecuteNonQuery();
command.Connection.Close();
}
return returnDeleted.ToString();
}
I've been told to use Auto Incrementing ID from SQL so that each row will have a unique ID so I can delete only the selected lines. However, I don't even have a clue how to do that. I've already turned on the identity option in SQL for the itemcode column, but aside from that, I'm lost. How do I go about using that ID to delete only selected items from the checkbox list in asp?
When you say the items are "exactly the same", do you mean that they have the same item code? And item codes are allowed to be duplicated in your system (i.e. is that the correct business rule)?
If so, that's why you need a auto-generated ID for each line, so that each row is unique. Which means that you need to use that ID in your DELETE query instead of the item code.
Typically, in a (ASP.NET) web app, this sort of thing is done with a "grid". You can use a GridView with two columns: one is a checkbox and another column is just a label showing the item code. Each row is bound to the ID field.
So, I recommend that you start by checking out GridView (there's lots of examples out there on the web): MSDN documentation for GridView
I'm teaching myself C# in VS2012 on 4.5 framework and loving it, but this is (continuing to) baffle me, so I apologize if I'm missing something obvious. I have done some new testing (since my original post 3/23) and am now more confused.
I added a DataSet item to my project called reviews.xsd.
I programmatically fill the DataSet with all data from Review table, then add two new fields to the Columns collection, then use EntityFramework to join to the Book table to add the data for those two new fields. I programmatically link the GridView control (dgvReviews) to this populated DataSet and everything displays great when I open the page, so all the data population into the DataSet and the linked GridView control is working great.
HOWEVER, the Columns collection of the GridView control is strangely EMPTY, so I can't change the styles of the columns or hide or show them using the Visible property. The Columns collection of the DataSet that populates the GridView is complete those values are accessible normally.
I have set numerous Watches to look at other properties of the GridView control and they seem to be populating normally: the Rows collection, for example, displays the values through the Watch window, but all access to the Columns collection displays "Enumeration yielded no results," even though the data is all displaying correctly (when I don't try to access the Columns collection explicitly in code).
I'm a beginning programmer so any advice would be much appreciated.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// create reviews dataset, populate with standard data from Review table
reviews reviewDataSet = new reviews();
reviewsTableAdapters.reviewTableAdapter reviewDataAdapter = new reviewsTableAdapters.reviewTableAdapter();
reviewDataAdapter.Fill(reviewDataSet.review);
reviewDataSet.review.Columns.Add("bookName", typeof(string));
reviewDataSet.review.Columns.Add("bookDescription", typeof(string));
reviewDataSet.review.Columns["bookName"].SetOrdinal(3);
reviewDataSet.review.Columns["bookDescription"].SetOrdinal(4);
// use EF to populate data from Book table into new bookName and bookDescription fields
bookReviewsEntities bookConnection = new bookReviewsEntities();
foreach (reviews.reviewRow reviewEntry in reviewDataSet.review)
{
int bookNumber = reviewEntry.bookID;
var bookLookup = (from book in bookConnection.books
where book.bookID == bookNumber
select book).ToList();
reviewEntry.BeginEdit();
reviewEntry["bookName"] = bookLookup[0].title;
reviewEntry["bookDescription"] = bookLookup[0].description;
reviewEntry.EndEdit();
}
bookConnection.Dispose();
// next 2 lines verify the Columns collection of the DataSet is working fine
string test1 = reviewDataSet.review.Columns[0].ToString();
string test2 = reviewDataSet.review.Columns[1].ToString();
dgvReviews.DataSource = reviewDataSet.review;
dgvReviews.DataBind();
// everything runs and displays normally if next line is commented out
dgvReviews.Columns[0].Visible = false; // crashes with "index out of range" since "Columns" collection is empty
}
}
For the Columns property to be accessible you need to list your columns in your GridView declaration like below and disable the auto generation of columns with AutoGenerateColumns="false"
<Columns>
<asp:BoundField DataField ="Id" />
<asp:BoundField DataField ="First" />
<asp:BoundField DataField ="LastName" />
</Columns>
When Columns are auto generated you can't access the Columns property.
I am populating all Transaction data on one button click in a GridView. However, Transaction table in the database does not contain Dimension table (e.g. Account table) data such as Transaction table contains AccountID but it does not have AccountName property which I have to bring from the Account table. In the DataAccess layer the method (GetAllTransactions()) does contain the join between Transaction and Account table on AccountID, but when I try to select account.AccountName it does not work.
I just need to show few tables from Transaction table where the AccountID mataches and show the AccountName column instead of AccountID from the Transaction table.
The DataAccess method looks like:
public static IEnumerable<Transaction>GetAllTransactions()
{
List<Transaction> allTransactions = new List<Transaction>();
using (var context = new CostReportEntities())
{
allTransactions = (from t in context.Transactions
join account in context.Accounts on t.AccountID equals account.AccountID
select t).ToList();
}
return allTransactions;
}
and the Code behind the .aspx page is as follows:
protected void _UIButtonSubmit_Click(object sender, EventArgs e)
{
IEnumerable<Transaction> transactions = ts.GetAllTransactions();
_UITransactionGridView.DataSource = transactions;
_UITransactionGridView.DataBind();
_UITransactionGridView.PageIndex = 0;
}
tried few things with the following also, but I am not getting the LINQ idea. The following gives error.
...select new {t.*, account.AccountName}).ToList();
I need a direction which way should I be looking at to make the task work to populate data from multiple tables in one GridView. Thanks.
Since my Model for Transaction did not have any property of Account table I had to create a ViewModel type class which returns custom data of AccountNumber for every Transaction.
Tha code that I used to solve the problem is this
I have to tables:users and messages.And create the one-many relations between these tables.And,If I display this two table in single xtragrid, it's no problem,But ,I want to display into two grid,the detail of messages doesn't display. please help me!
the key code is :
1.create the dataset of users and messages:
DataSet ds = new DataSet();
ds = SqlHelper.ExecuteDataset(fbh.ConnectionString, CommandType.Text, s);
DataTable mess = ds.Tables[0];
mess.TableName = "Messages";
DataTable user = deptmentUserMessages.Tables["Users"];
DataTable m = new DataTable("Messages");
m.Merge(mess);
deptmentUserMessages.Tables.Add(m);
deptmentUserMessages.Relations.Add("**UserMessages**", user.Columns["UserName"], m.Columns["SENDER"]);
the deptmentUserMessages is the static dataset
2.in the form.load event,I have to do:
gcMessage.DataSource = master;
gcMessageDetail.DataSource = detail;
master.DataSource = pub.DeptmentUserMessages;
master.DataMember = "Users";
detail.DataSource = master;
detail.DataMember = "**UserMessages**";
the master and detail are BindingSource.
You should handle xtargrid FocusedRowChanged event to populate detail grid.
Get the primary key field value to fetch values from child table and then set the data source of child grid. Use GetRowCellValue(Int32,String) Method
private void gridView1_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e) {
if(e.FocusedRowHandle >=0)
{
/// Get master table selected row's primary column value
/// then create a DataView from the detail table
// and set datasource of detail grid.
dvUserMessages = (Filtered row by primary column value);
master.DataSource = dvUserMessages.ToTable();
}
}
Reference:Parent - Child relationship between Two GridViews
Using only event FocusedRowChanged is not enough. When the DataSource is changed, this event doesn't fires. Because the position property doesn't changes, it remains 0. And it doesn't fires when user filters rows in master grid. So, add to this example similar event handler on ColumnFilterChanged event, and also populate child grid just after setting DataSource property of master grid.
I am playing about just now trying to teach myself a little bit about the entity framework.
I have a Gridview data bound to a Entity Date Source using the Entity Framework. If I select certain items in that list I then wish to redirect another page and populate another gridview with just the items selected (but with more detail, different includes/navigation properties)
This is probably the most simple thing but I have spent 2 hours banging my head on the wall trying to get this to work.
Essentially I have a continue button which when clicked should identify all the UIDs (a column in the gridview) of the rows and allow me to subset to just these rows and pass them to another page to be rebound to another datagrid
Any ideas???
Well, the big picture is that you should get those IDs, pass them to the other page, and then use a query with Contains; see this question for an idea of how to use it:
How search LINQ with many parametrs in one column?
Assuming you haven't used DataKeys in your GridView, this would be my approach.
Page 1
protected void Button1_Click(object sender, EventArgs e)
{
var checkedItems = new List<int>();
foreach (GridViewRow row in GridView1.Rows)
{
var checkbox = (CheckBox)row.FindControl("CheckBox1");
if (checkbox.Checked)
{
checkedItems.Add(int.Parse(row.Cells[1].Text));
}
}
Session["checkedItems"] = checkedItems;
Response.Redirect("Page2.aspx");
}
Page 2
protected void Page_Load(object sender, EventArgs e)
{
var checkedItems = (List<int>)Session["checkedItems"];
Session["checkedItems"] = null;
foreach (var checkedItem in checkedItems)
{
Response.Write(checkedItem);
}
}
Using the IDs in the checkedItems List you can now query those from you DB and finally assign the Result to your GridView on the second page.
Instead of using Session you could pass the IDs via QueryString.