I'm getting this error: Cannot bind to the new display member C#
sConn = new SqlConnection(sStr);
daSched = new SqlDataAdapter("Select Subject from Schedules where Username = '" + lblUsername.Text + "'", sConn);
dsSched = new DataSet();
daSched.Fill(dsSched, "Schedules");
dsSched.Tables["Schedules"].PrimaryKey = new DataColumn[] { dsSched.Tables["Schedules"].Columns["ScheduleID"] };
cbxSubject.DataSource = dsSched.Tables["Schedules"];
cbxSubject.DisplayMember = "Schedule";
cbxSubject.ValueMember = "ScheduleID";
cbxSubject.Text = "Choose Subject";
I don't know where went wrong. This is the preview of the table Schedules: http://i47.tinypic.com/1zzoz5z.png
Thanks for any help.
You don't have a field in your table called "Schedule", so there is no member the control can find called Schedule, and you have selected only Subject
ScheduleID is already your primary key, so you're better of changing your Sql Query to:
Select ScheduleID, Subject From... (also you probably should parameterize it)
This line -> dsSched.Tables["Schedules"].PrimaryKey = new DataColumn[] { dsSched.Tables["Schedules"].Columns["ScheduleID"] }; is unnecessary.
From what I can tell I beleive you want your display member to be the "Subject"
Also - you should Open your connection (I don't see it in your post) - and more ideally wrap it in a using statement
Something like:
using (SqlConnection con = new SqlConnection(connectionString))
{
string userName = lblUsername.Text;
con.Open();
var adapter = new SqlDataAdapter("Select ScheduleID, Subject From
Schedules Where Username = #username", conn);
adapter.Parameters.Add("#username", SqlDbType.VarChar, 50, userName)
var dsSched = new DataSet();
adapter.Fill(dsSched);
cbxSubject.DataSource = dsSched.Tables[0];
cbxSubject.DisplayMember = "Subject";
cbxSubject.ValueMember = "ScheduleID";
cbxSubject.DataBind();
}
Related
I want to grab data from database and display in labels based on what the user selects in the list view.
I'm going off an example that does this with two list views, but I don't know how to do it when I'm sending data to a label.
This is the list view example I'm using (my label code is below this)
private void PopulateRecipeIngredients()
{
string query = "SELECT a.Name FROM Ingredient a " +
"INNER JOIN RecipeIngredient b ON a.Id = b.IngredientId " +
"WHERE b.RecipeId = #RecipeId";
// # is a parameter
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
// whatever recipe is selected in lstRecipes box, get the id of that and pass into query above
command.Parameters.AddWithValue("#RecipeId", lstRecipes.SelectedValue);
// DataTable holds the data return from query
DataTable ingredientTable = new DataTable();
// SqlDataAdapter object adapter fills the ingredientTable DataTable object with results from query
adapter.Fill(ingredientTable);
// Display value of Name ex. salad
lstIngredients.DisplayMember = "Name";
// Id column is how we reference
lstIngredients.ValueMember = "Id";
// connect list box on form to data in recipeTable
lstIngredients.DataSource = ingredientTable;
}
}
MY CODE:
private void PopulateCourseDetails()
{
string query = "SELECT * FROM Course_Info WHERE Id = #CourseId";
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
command.Parameters.AddWithValue("#CourseId", lstCourses.SelectedValue);
DataTable courseTable = new DataTable();
adapter.Fill(courseTable);
lblCourseId.Text = "Course_id";
lblCourseSection.Text = "Course_section";
lblCourseName.Text = "Course_name";
lblCourseDay.Text = "Course_day";
lblCourseStartTime.Text = "Course_start_time";
lblCourseEndTime.Text = "Course_end_time";
lblCourseProfessor.Text = "Course_professor";
lblCourseProfessorEmail.Text = "Course_professor_email";
lstCourses.ValueMember = "Id";
}
}
lblCourseId.Text = (string)courseTable.Rows[0]["Course_id"]
should work as long as you have one row in the result table
Assuming that your DataTable has now been properly populated, you now have a table with a number of rows.
First you need to pull out the first row
var row = courseTable.Rows.FirstOrDefault();
Now you've got a row with a number of columns. You can access each column by either index or column name.
lblCourseId.Text = row[0];
If you want the label to maintain it's header, you can do something like
lblCourseId.Text = "Course_id: " + row[0];
When I try to run the program, I get this error and I cant solve it. Is it because I am trying to get the data from the same method.
rivate void populateTableTopping()
{
string query = "SELECT a.Name FROM Toppings a " +
"INNER JOIN Table b ON a.Id = b.ToppingsId " +
"WHERE b.TypeId = #TypeId";
using (Connection = new SqlConnection(connectionstring))
using (SqlCommand command = new SqlCommand(query, Connection))
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
command.Parameters.AddWithValue("#TypeId", sizeTypeListBox.SelectedValue);
DataTable tableToppingTable = new DataTable();
adapter.Fill(tableToppingTable);
tableToppingListBox.DisplayMember = "Name";
tableToppingListBox.ValueMember = "Id";
tableToppingListBox.DataSource = tableToppingTable;
}
}
and get this error: in Adapter.fill
System.ArgumentException: 'No mapping exists from object type System.Data.DataRowView to a known managed provider native type.'
sizeTypeListBox.SelectedValue is a System.Data.DataRowView and TypeId is not. They don't match.
Do you want the displayed text?
var text = sizeTypeListBox.GetItemText(sizeTypeListBox.SelectedItem);
command.Parameters.AddWithValue("#TypeId", text);
I am a .Net developer and I am searching for a question that how can I filter combobox values bound from a SQL Server 2012 database.
I have four comboboxes as seen in the Registration Form. I want to filter the values of all these comboboxes as if I select the value in first combobox that value should not be displayed in the other comboboxes.
I am using Visual Studio 2013.
Here is the code for first combobox of Course Name Field:
public void BindData()
{
objcon.Open();
string cmd = "select Course_Name from CourseDetails";
objcom = new SqlCommand(cmd, objcon);
objDA = new SqlDataAdapter(cmd, objcon);
objDS = new DataSet();
objDA.Fill(objDS);
objcom.ExecuteNonQuery();
objcon.Close();
CmBx_Course_Name1.DisplayMember = "Course_Name";
CmBx_Course_Name1.ValueMember = "Course_Name";
CmBx_Course_Name1.DataSource = objDS.Tables[0];
CmBx_Course_Name1.Enabled = true;
}
Here is the code for first combobox of Batch Name Field:
public void BindBatchName()
{
objcon.Open();
string cmd = "select Batch_Name from batch where Batch_Status IS NULL";
objcom = new SqlCommand(cmd, objcon);
objDA = new SqlDataAdapter(cmd, objcon);
objDS = new DataSet();
objDA.Fill(objDS);
objcom.ExecuteNonQuery();
objcon.Close();
CmBx_batch_name1.DisplayMember = "Batch_Name";
CmBx_batch_name1.ValueMember = "Batch_Name";
CmBx_batch_name1.DataSource = objDS.Tables[0];
CmBx_batch_name1.Enabled = true;
}
I checked this query over and over again and I cant tell what the problem is.
using (OleDbConnection connection = getConnection())
{
string update =
"UPDATE Course SET SchoolID = #SchoolID, SchoolID2 = #SchoolID2, StatusID = #StatusID," +
"Bannercode = #Bannercode, CourseName = #CourseName, Description = #Description, Credits = #Credits," +
"Prereqs = #Prereqs, URL = #URL, Keywords = #Keywords, Email = #Email, Approved = #Approved, ApprovedBY = #ApprovedBY," +
"ApprovedWhen = #ApprovedWhen, History = #History, Level = #Level WHERE ID = #ID";
OleDbCommand command = new OleDbCommand(update,connection);
OleDbParameter pram1 = new OleDbParameter("#SchoolID", SchoolID);
command.Parameters.Add(pram1);
OleDbParameter pram2 = new OleDbParameter("#SchoolID2", SchoolID2);
command.Parameters.Add(pram2);
OleDbParameter pram3 = new OleDbParameter("#StatusID", StatusID);
command.Parameters.Add(pram3);
OleDbParameter pram4 = new OleDbParameter("#Bannercode", Bannercode);
command.Parameters.Add(pram4);
OleDbParameter pram5 = new OleDbParameter("#CourseName", CourseName);
command.Parameters.Add(pram5);
OleDbParameter pram6 = new OleDbParameter("#Description", Description);
command.Parameters.Add(pram6);
OleDbParameter pram7 = new OleDbParameter("#Credits", Credits);
command.Parameters.Add(pram7);
OleDbParameter pram8= new OleDbParameter("#Prereqs", Prereqs);
command.Parameters.Add(pram8);
OleDbParameter pram9 = new OleDbParameter("#URL", URL);
command.Parameters.Add(pram9);
OleDbParameter pram10 = new OleDbParameter("#Keywords", Keywords);
command.Parameters.Add(pram10);
OleDbParameter pram11 = new OleDbParameter("#Email", Email);
command.Parameters.Add(pram11);
OleDbParameter pram12 = new OleDbParameter("#Approved", Approved);
command.Parameters.Add(pram12);
OleDbParameter pram14 = new OleDbParameter("#ApprovedBY", ApprovedBY);
command.Parameters.Add(pram14);
I suppose that you are using MS-Access as database behind the OleDb. If this is the case then the LEVEL word is a reserved keyword and you need to put it between square brackets
... [Level] = #Level WHERE ID = #ID";
Your code could be better written if you use a different method to prepare the parameter collection.
For example
command.Parameters.Add(new OleDbParameter("#Prereqs", OleDbType.Integer).Value = Prereqs;
Specifying the OleDbType of the parameters helps the engine to disambiguate between the Value and the Type when the Value is zero.
Look at this article on MSDN that explain why you should avoid using this form of the Add method of the OleDbParameterCollection (The article is for SqlParameterCollection but the same is true for OleDb)
I am just playing around with this at the moment, ultimately I want to read a CSV file into memory and then insert the records into an SQL database. Existing records should be updated, records that are missing should be added. Records that don't exist in the new CSV shouldn't be deleted, however.
I've been playing around the example from the MSDN library. I understand that the SqlDataAdapter can perform bulk updates quite quickly.
I created a little mock app with a table called TempTestTable that has TempTestTableId, Age, and Name columns. I wrote this (based on the MSDN Article):
using (SqlConnection connection =
new SqlConnection("data source=localhost;initial catalog=fishsticks;integrated security=True;MultipleActiveResultSets=True;"))
{
SqlDataAdapter dataAdpater = new SqlDataAdapter(
"SELECT temptesttableid, Age, Name FROM TempTestTable",
connection);
dataAdpater.UpdateCommand = new SqlCommand(
"UPDATE TempTestTable SET Age = #Age, Name = #Name " +
"WHERE TempTestTableId = #TempTestTableId", connection);
dataAdpater.InsertCommand = new SqlCommand(
"INSERT INTO TempTestTable (Age, Name) " +
"VALUES (#Age, #Name)", connection);
SqlParameter parameter = dataAdpater.UpdateCommand.Parameters.Add(
"#TempTestTableId", SqlDbType.Int);
dataAdpater.InsertCommand.Parameters.Add(
"#Age", SqlDbType.Int, 10, "Age");
dataAdpater.InsertCommand.Parameters.Add(
"#Name", SqlDbType.NVarChar, 50, "Name");
dataAdpater.UpdateCommand.Parameters.Add(
"#Age", SqlDbType.Int, 10, "Age");
dataAdpater.UpdateCommand.Parameters.Add(
"#Name", SqlDbType.NVarChar, 50, "Name");
parameter.SourceColumn = "TempTestTableId";
parameter.SourceVersion = DataRowVersion.Original;
DataTable tempTestTable = new DataTable();
tempTestTable.Columns.Add("Age");
tempTestTable.Columns.Add("Name");
tempTestTable.Columns.Add("TempTestTableId");
var row1 = tempTestTable.NewRow();
row1["Age"] = 10;
row1["Name"] = "Smith";
row1["TempTestTableId"] = 1;
var row2 = tempTestTable.NewRow();
row2["Age"] = 40;
row2["Name"] = "Jones";
row2["TempTestTableId"] = 2;
tempTestTable.Rows.Add(row1);
tempTestTable.Rows.Add(row2);
dataAdpater.Update(tempTestTable);
There is already a record in the database with TempTestTableId = 1, so the idea was that in theory it would update that record, as well as insert a new record with ID 2. However, when I run the code, it inserts both items.
Any ideas?
No, the DataAdapter will just look at the DataRow's RowState property. If it's Added the InsertCommand will be executed, if it's Modified the UpdateCommand will be executed. You have to load this row into the table from the database first.
You can fill an empty DataTable with a DataAdapter and your SelectCommand including two parameters. If the table is empty you can add the DataRow manually, otherwise you can modify the rows with the updated values (if any) and call dataAdpater.Update(tempTestTable).
Here's an example (untested):
SqlDataAdapter dataAdpater = new SqlDataAdapter(
"SELECT temptesttableid, Age, Name FROM TempTestTable WHERE Name = #Name",
connection);
DataTable testTable = new DataTable();
// note that you should use an available csv-parser instead
foreach (string line in File.ReadAllLines(path))
{
string[] columns = line.Split(new char[]{'\t'}, StringSplitOptions.None);
if(columns.Length >= 2)
{
string name = columns[0].Trim();
string ageStr = columns[1].Trim();
int age;
if (int.TryParse(ageStr, out age))
{
dataAdpater.SelectCommand.Parameters.AddWithValue("#Name", name);
int rowsAdded = dataAdpater.Fill(testTable);
if (rowsAdded == 0)
{
testTable.Rows.Add(name, age);
}
else
{
// update values?
}
}
}
}
dataAdpater.Update(testTable);