Taking Value of dropdownlist in asp.net - c#

After using inner joins and fetching data from 3 tables I want to show course names that are assigned to Miss Jennifer whise Tchr_ID is 4 , ddlcourse is dropdown list id
SqlCommand cmd = new SqlCommand(#"
SELECT
Course.Course_name,
Tchr_course_ID
FROM Course
INNER JOIN CourseOffering
ON Course.Course_ID=CourseOffering.Course_ID
INNER JOIN Tchr_Course
ON Tchr_Course.Course_offer_ID=CourseOffering.Course_offer_ID
where Tchr_Course.Tchr_ID = 4", conn);
SqlDataReader dr = cmd.ExecuteReader();
ddlcourse.DataSource = dr;
ddlcourse.Items.Clear();
ddlcourse.DataTextField = "Course_name";
ddlcourse.DataValueField = "Tchr_course_ID";
ddlcourse.DataBind();
After fetching I am showing dropdown textfield as course name and I am applying datavaluefiled as tch_Course_ID because when user will select the course , its tchr_course_ID will be saved in db. to save id I am using ddlcourse.SelectedItem.Value but this gives me error in my insert statement about foreign key. It is not taking value of selected course. Why? and how can I correct it?
These tables are involved in it..
Course table:(which have courses list in it) ==>
(Course_ID,Course_name)
CourseOffering table: (which have record that these courses are
offered this semester) ==> > (Course_offer_ID, Course_ID)
Tchr_Course table: (which have record that this course is assigned to
this teacher) ==> (Tchr_course_ID, Course_offer_ID, Tchr_ID)
Profile table: (simple contains teacher record) == >
(Tchr_ID,NAme,Email)

Use SelectedValue instate of using SelectedItem.Value since ur ddlcourse has DataValueField as Tchr_course_ID hence only SelectedValue gives u required result for Tchr_course_ID.

Related

How can I set a ComboBox initial DisplayMember to show the correct item depending on the ID taken from SQL Server

I wrote a Windows Forms application that gets all the data from a SQL Server.
The first form shows a DataGridView with Receipts, each receipt has its ID number, Name and Status which can be Active or Paid.
ID | Name | Status
---+-----------+----------
1 | Receipt22 | Active
When a receipt is selected from the DataGridView and the "Edit" button is clicked, it will prompt the second form in which all the Items / Products are displayed for said receipt.
Now, my question is, I successfully filled the ComboBox with all the items from the Products table, but what I need to do. Is to set the initial DisplayMember of a row, to be that of an Item that has been selected.
So for example if "Receipt1" has Products "1,2,2,3,4,1" to it, it should display in each row, a ComboBox where the initial value member is equal to the ID of the Product.
using (SqlConnection sqlCon = new SqlConnection(ConnectionStringHelper.ConString("Name")))
{
SqlDataAdapter sdr = new SqlDataAdapter("Select * from Products", sqlCon);
DataTable dt = new DataTable();
sdr.Fill(dt);
txtComboProducts.ValueMember = "ProductsID";
txtComboProducts.DisplayMember = "ProductName";
txtComboProducts.DataSource = dt;
}
This is how I fill the ComboBox itself, but I do not know how to show and add a row depending on the item that is in correspondence to the Receipt.
So, in this case where the items would be "1,2,2,3,4,1", let's say 1 = Water, 2 = Juice, 3 = Candy, 4 = Cake
Products(this is the comboBox) | Quantity |
-------------------------------+----------+
Water 2
Juice 1
Juice 2
Candy 5
Cake 1
Water 4
and now if I would like to change let's say Row 1, I could just select the comboBox and change it to some other Product on the list.
The main problem is that, I do not know how to set the initial DisplayMember and how to add new Row for each of the items.
Does anyone have any ideas or advice? Would be appreciated.
DisplayMember is the name of the field to display and will always stay the same (e.g. the product name).
You need at least three tables. A Receipts table, a Products table and a junction table that assigns products to receipts. Let's call it ReceiptProducts.
Then to fill the combo box, you must execute query which goes like this
SELECT rp.ProductsID, p.ProductName
FROM
ReceiptProducts rp
INNER JOIN Products p
ON rp.ProductsID = p.ProductsID
WHERE
rp.ReceiptsID = 7 -- Assuming that this is the id of your current receipt
ORDER BY
rp.Sorting
Tables:
Receipts (PK ReceiptsID, ReceiptName, Description etc.)
Products (PK ProductsID, ProductName)
ReceiptProducts (PK ReceiptProductsID, FK ReceiptsID, FK ProductsID, Quantity, Unit, Sorting)
If you want to display different items in the combo box for each data grid row (this has nothing to do with DisplayMember), load the combo box items in the DataGridView.RowEnter Event.
DataTable dt;
void LoadC()
{
using (cnx = new SqlConnection("Var_Connection"))
{
cnx.Open();
var adapt = new SqlDataAdapter("select * from Products", cnx);
dt = new DataTable();
adapt.Fill(dt);
comboBox1.DisplayMember = "ProductName";
comboBox1.ValueMember = "ProductsID";
comboBox1.DataSource = dt;
}
}

C# SQL Is it possible to insert from a joined table into datagridview

I have four tables in my SQL database
In C# I have made a datagridview which shows the DeliveryDate, Quantity, Description and Price from the Order, Linkedtable and Stock table being joined in a select statement.
Here is the code used to join three tables into one datagridview
// this code for the load button of the datagridview
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("SELECT O.DeliveryDate, L.Quantity, S.Description, S.Price FROM [Order] O JOIN Linkedtable L ON O.OrderID = L.OrderID JOIN Stock S ON S.StockID = L.StockID ORDER BY O.DeliveryDate ", con);
DataTable DATA = new DataTable();
sda.Fill(DATA);
dataGridView1.DataSource = DATA;
con.Close();
This is how the datagridview looks
I would like to insert DeliveryDate, Quantity, Description and price from four textboxes into datagridview but i'm not sure how to do an INSERT statement with the tables joined like i have with the SELECT statement, is there a way to do this?
Since data will reside in different tables, there is no way to insert them at once and therefore, you can't execute it with one single command. However, you can create a store procedure to insert data into different tables separately, or you can insert them with two different INSERT commands in one batch.

How to handle identity column in datagridview?

I created a table in a database with identity column called id . when i delete data from this table and add new data the id column is still increased by 1 , i need to make this column start increasing from the last id inside this table not the deleted one what should i do ?
this is the datagridview with some records:
this is the delete code
if (comboBoxdelete.SelectedIndex != -1)
{
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
con.ConnectionString = "Data Source=MOHAMEDSAFWAT;Initial Catalog=Card;Integrated Security=True";
cmd.CommandText = "DELETE FROM [Employee] WHERE [int]=#id1";
cmd.Connection = con;
cmd.Parameters.AddWithValue("#id1", comboBoxdelete.SelectedItem);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
load();
View();
}
else
{
MessageBox.Show(" Please Insert ID First");
}
Identity column (in SQL-Sever) is handled by by RDBMS. It will be increased any time you add some row to the table, when removing rows the RDBMS will not rollback the underlying sequence of the identity column.
Id or primary key of your tables are for internal usage of your application. normaly you must not show them to the user.
do not use the id column as row number for end user (as any thing is showing to the user will be compromizer to be requested to be updated or deleted)
By the way lets think we need to implement the id column manually to full fill your requiment.
We can use a simple approach: When adding any new row first we call a select to fetch the new id:
SELECT ISNULL(count(*),0)+ 1 as newid from Employee
We will have the new id.
know the delete scenario, think that we have
Employee1-->id = 1
Employee2-->id = 2
Employee3-->id = 3
Employee4-->id = 4
Now we delete Employee2 so what is needed to be done?
We need updates(after detecting rows to be updated) like this, to achieve your requirement:
Update Employee3 set id = 2
Update Employee4 set id = 3
For all rows in the table!
It will not work in large amount of data, id is the primary key when updating, all child records must also be updated, re-indexing, table locking and ... will be inevitable.
All this is because the id column is being showed to the user and you need that to be shown sequentially.
Use another non key column like Employee-Number or a UI level column like RowNumber for these scenario and do not show your primary key to the user.

Prevent duplicate results in SQL

I have a combo box (comboBox1) in my application that lists catagories from my SQL database. It is pulling the data correctly at the moment. My only problem is that when the data is listed in the combo box, there are duplicate results. For example:
What I want it to list:
Example 1
Example 2
Example 3
What it actualy lists:
Example 1
Example 1
Example 1
Example 1
Example 1
Example 2
Example 2
Example 2
Example 3
Example 3
Example 3
Here is the code that I am using to list the data:
public void ListCat()
{
DataTable linkcat = new DataTable("linkcat");
using (SqlConnection sqlConn = new SqlConnection(#"Connection stuff;"))
{
using (SqlDataAdapter da = new SqlDataAdapter("SELECT name FROM list WHERE name <> 'NULL'", sqlConn))
{
da.Fill(linkcat);
}
}
foreach (DataRow da in linkcat.Rows)
{
comboBox1.Items.Add(da[0].ToString());
}
}
In short, my question would be how can I prevent duplicate data from being listed?
Use DISTINCT . It will eliminate the duplicate records.
Change your query to
SELECT DISTINCT name FROM list WHERE name <> 'NULL'
Assuming you may have stored the string value NULL inside your name column for some records.
If you have the real NULL in the name field, your query should be like this
SELECT DISTINCT name FROM list WHERE name is not NULL
Use DISTINCT
SELECT DISTINCT name FROM list WHERE name <> 'NULL'
Add a group by to the SELECT statement.
SELECT name FROM list WHERE name <> 'NULL' GROUP BY name

problem updating dropdownlist

I have a problem while updating changing the item in dropdownlist.
I have a dropdownlist which is populated in code behind file.
Here is the code:
departmentComm = new SqlCommand("SELECT DepartmentID, Department FROM Departments", conn);
conn.Open();
reader = departmentComm.ExecuteReader();
// Populate the list of categories
departmentList.DataSource = reader;
departmentList.DataValueField = "DepartmentID";
departmentList.DataTextField = "Department";
departmentList.DataBind();
// Close the reader
reader.Close();
I select one value from this list and saves it in my employee table. Now let's suppose I want to update this value in employee table.
Now my question is, how can I pull this value in dropdownlist and show it?
If you just van to get the selected department id:
departmentList.SelectedValue
gives you the id
If you embedded the dropdown in a datagrid you will need to update the database using a DataAdapter and call its Update method.
If you need more specifics you need to give more details.

Categories

Resources