How to populate database information from dropdown selection? - c#

I have a students table, a courses table and a student/courses table to show the students enrolled in a course. The table is in SQL Server 2008 and the front end in C# and Asp.net.
In the student/courses table I would like to be able to have a dropdown menu that will allow me to select the student ID stored on the database and then populate the student's name, last name and middle initial in a textbox or label.
How can I possibly do this? Any examples? Thank you for your help!

You can use either ADO.net, if not familiar then
on page load event
SqlCommand cmd = new SqlCommand();
cmd.Connection= new Class1().getconnection();
cmd.CommandText = "SELECT * FROM Profile";
cmd.Connection.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
DropDownList1.Items.Add(dr["YahooId"].ToString());
}
in "cmd.CommandText" instead of "Profile" use your table name, and under "while(dr.read()) use your column name instead of "YahooId"

Related

How can I make it so only the logged in user view his own grade?

This is the student info table where the student info comes from //This is the login code for the user and it get the user log in info from the studentinfo table.
private void btnlogin_Click(object sender, EventArgs e)
{
i = 0;
con.Open();
MySqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from stdinfotable WHERE Username='" + textuser.Text + "' and Password= '" + textpass.Text + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
MySqlDataAdapter dta = new MySqlDataAdapter(cmd);
dta.Fill(dt);
i = Convert.ToInt32(dt.Rows.Count.ToString());
if(i==0)
{
MessageBox.Show("Error");
}
else
{
this.Hide();
StudentPage f = new StudentPage();
f.Show();
MySqlDataAdapter data = new MySqlDataAdapter("ViewAllGrades", con);
data.SelectCommand.CommandType = CommandType.StoredProcedure;
DataTable dtTable = new DataTable();
data.Fill(dtTable);
dtTable.Select("Last_Name");
f.stdGrade.DataSource = dtTable;
f.stdGrade.Columns[0].Visible = false;
}
con.Close();
}
This is the ViewlAllGrades stored procedure where the grade info is returned from
CREATE DEFINER=`root`#`localhost` PROCEDURE `ViewAllGrades`()
BEGIN
SELECT *
FROM Grades;
END
I am trying to make it so only the logged in user can view his own grade rather than viewing every user grade. So I am wondering should I try to do within the stored procedure or in Visual Studio and how would I achieve such thing? Also my primary keys which are ID are from both table are auto incremented so I cant not necessarily use those
Right now your stored procedure is selecting all of the grades. First thing to do would be to parameterize the query, accepting the user as the input, and using the WHERE clause to find only the grades for that student. Without seeing your tables, I cannot tell you exactly what this would look like, but as an example: SELECT * FROM Grades WHERE StudentId = #StudentId;
The second thing you need to figure out is how to get the current user's student id and then pass it to the stored procedure. Again, without seeing your tables, I can hardly guess. It appears you already have the username of the current user. Are you able to run a query to find the studentId from the username? If so, then you first need to run that procedure with username as the parameter to get the studentId.
A third concern is with your first query. Since it has not been parameterized, it is susceptible to SQL injection attacks. This poses a MAJOR security risk. If someone maliciously enters a username or password, they can escape the SQL you intended to run and drop all of your tables.
Hopefully that helps!

How can I delete a single entry from a table

I have a listbox with usernames, and a remove button I want the selected a user (with all entered data associated with that user) to be deleted when the remove button is clicked.
My code
SqlConnection con = new SqlConnection("Data Source=JAMES-PC\\SQLEXPRESS;Initial Catalog=staff;Integrated Security=True");
con.Open();
string sql = #"DELETE FROM staff1;";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
con.Close();
this code deletes the whole table.
How can I just delete the selected user?
You need a WHERE clause to select the required record. You have to get the username of the selected user to be deleted and pass it to #UserName parameter.
var userName = (listBox.SelectedItem as DataRowView)["UserName"].ToString();
string sql = #"DELETE FROM staff1 WHERE Username = #UserName;";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#UserName",useName);
cmd.ExecuteNonQuery();
con.Close();
See this thread on how to use parameters in the SQL.
When you execute a delete query, in order to delete only 1 row from the table you need to add a WHERE clause.
Based on the comments the workflow should be something like: you click on a delete button, you send the name of the staff you want to delete to the command, which looks like:
string sql = #"DELETE FROM staff1 where Name=#Name;";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#Name","NameReceivedFromList");
cmd.ExecuteNonQuery();
con.Close();
When you are deleting you should remember to add a Where clause, it is actually very powerfull here is some examples that will get you started
The following query will delete only one element
DELETE FROM Table WHERE Table.PrimaryField = Value
The following query will delete all items that matches
DELETE FROM Table WHERE Table.Field = Value
You can also have a join in your delete statement for more complex delete queries
DELETE A FROM Table A
INNER JOIN TableB B ON A.Key = B.Key
WHERE B.PrimaryField = Value

How to display values into gridview from sql databese

In my database i have three tables. One For employs where i keep their names, ids, salary... In the second one named Project i keep id, location, name. in the third one named WorksOn i keep the id from employs and the id from project. In my Asp .Net web site in gridview i need to display the employee's name and the name of the project that he is working.
string connect =
WebConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
SqlConnection con = new SqlConnection(connect);
try
{
con.Open();
}
catch (Exception err)
{
string error = err.Message;
con.Close();
}
SqlCommand command = new SqlCommand();
command.Connection = con;
SqlDataReader reader;
command.CommandText = "SELECT * FROM WorksON ";
reader= command.ExecuteReader();
In data source in gridview if i choose to display the values from WorksOn table it shows the id from employs and the id from project but what i need is to show the names on the employs and project.
I know that i need to do something with dataset but i don't know who.
Your SQL command must JOIN the related tables. Something like:
SELECT * FROM WorksOn JOIN Employee on WorksOn.EmployeeId = Employee.Id
Note that you should not SELECT "*" (all columns). You should only SELECT those columns that are necessary to your data view for performance.
On your SQL command, you don't mention anything about Employs. You need to use a JOIN SQL command in order to get both the employee name and the company name.
And instead of using "SELECT * FROM...", consider using the columns name instead, because you're not trying to get all the columns display. And it will help us understand the name of the columns to further help you.
Use a JOIN query like this:
SELECT project.projectName, employee.Name
FROM (worksOn
INNER JOIN employee
ON (worksOn.employeeId = employee.employeeId))
INNER JOIN project
ON (project.projectId = employee.employeeId)
AND (worksOn.projectId = project.projectId)

Why is "ORDER BY" breaking my query?

I'm using the code below to grab a list of companies from my database and load them into a list view. It's working great.
conn.Open();
string pricesqry = "SELECT company, url FROM companies";
SqlCommand pricescmd = new SqlCommand(pricesqry, conn);
SqlDataReader pricesreader = pricescmd.ExecuteReader();
while (pricesreader.Read())
{
ListViewItem company = new ListViewItem(pricesreader["company"].ToString());
company.SubItems.Add(pricesreader["url"].ToString());
company.SubItems.Add("Blank for now..");
pricesList.Items.Add(company);
}
conn.Close();
However, if I wanted to alphabetize my list by company names, by changing my select query to this:
string pricesqry = "SELECT company, url FROM companies ORDER BY company";
No data is loaded into the listview. Remove the order by section and the data appears again. What am I doing wrong?
In case you might have NULL's in database it would be better to get the values from reader like this:
Assuming company and url is a string.
ListViewItem company = new ListViewItem(Convert.IsDBNull(pricesreader.GetOrdinal("company")) ? null : pricesreader.GetString(pricesreader.GetOrdinal("company")));
company.SubItems.Add(Convert.IsDBNull(pricesreader.GetOrdinal("url")) ? null : pricesreader.GetString(pricesreader.GetOrdinal("url")));
hope this helps.
Credit goes to Minitech.
My 'Company' column type was set to Text. Changed to varchar and it's now working as I expected.

textbox search like in google

I am using C#.net Windows form , and I need to create a search textbox which will display combo box values (similar to google search); The values displayed in the combo box will be values from the SQL 2005 database (example the user is searching on FirstName, the combobox will display all firstnames, which get filtered as the user types in more letters.... if user is searching on LastName, the combo box displays all LastName values in the database.. etc)
when I am doing the above task
I have written the sql query like this
SELECT distinct(person_Firstname+''+person_Lastname)
AS
name FROM persondetails
WHERE name Like '%'+#name+'%'
when I am executing this query it gives error like this --- must declare a scalar varaible
my aim is when i am entering first letter in textbox it will display all names starting with that letter like in google...
can any one correct this ....
private void tbautocomplete_TextChanged(object sender, EventArgs e)
{
AutoCompleteStringCollection namecollection = new AutoCompleteStringCollection();
SqlConnection con = new SqlConnection(#"Data Source=88888;Initial Catalog=contrynames;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT distinct(person_Firstname+''+person_Lastname) AS name FROM persondetails WHERE name Like '%'+#name+'%'";
con.Open();
SqlDataReader rea = cmd.ExecuteReader();
if (rea.HasRows == true)
{
while (rea.Read())
namecollection.Add(rea["name"].ToString());
}
rea.Close();
tbautocomplete.AutoCompleteMode = AutoCompleteMode.Suggest;
tbautocomplete.AutoCompleteSource = AutoCompleteSource.CustomSource;
tbautocomplete.AutoCompleteCustomSource = namecollection;
It sounds like you're trying to build an AutoComplete feature in your app. You're only missing the parameter on your SqlCommand. Try this:
string searchFor = "%" + txtName.Text + "%"; //the string the user entered.
cmd.CommandText = #"SELECT distinct(person_Firstname+''+person_Lastname) AS name
FROM persondetails
WHERE person_Lastname Like #name
OR person_Firstname LIKE #name";
cmd.Parameters.AddWithValue("#name", searchFor);
Your WHERE clause must use the column name in your table. It sounds as if you want to match either the first or last name columns with your search token.
WHERE person_Lastname LIKE #name
OR person_Firstname LIKE #name
The functionality you're looking for is called AutoComplete. I'm not familiar with an AutoComplete control in Windows forms, but if there isn't a built in one, there will certainly be third-party controls that do this.
The AutoComplete control will likely provide an event callback where you can put your SQL query to provide the possible completions.
As for your SQL error, it looks like it might be an issue with column names, but it is difficult to tell without your schema.
Edit:
I see you're using an AutoComplete contol already. The problem in your SQL is that your #name parameter is in your query, but you haven't added the parameter to the cmd object, so it doesn't know what value to put there.

Categories

Resources