School Program Visual Studio 2022 C# & SQL server - visual-studio-2022

I am working on a school program im stuck at a point where I have a button and i want it to get the Highest grade of a certain Exam , i used the below code but didnt work i want the button to return a messagebox with the student name and exam name and grade which is the highest one, and to specify which exam im using a combobox with the list of exam names , noting that im using SQL management studio for database information and in the screenshot is the form design
SqlCommand cmd = new SqlCommand("SELECT COUNT(*) AS Expr1, ExamName, StudentName, MAX(Grade) AS Expr2 FROM Grades WHERE ExamName = #ex GROUP BY ExamName, StudentName, Grade ORDER BY Grade DESC", conn);
cmd.Parameters.AddWithValue("#ex", cbExam.SelectedValue.ToString());
conn.Open();
SqlDataReader rd = cmd.ExecuteReader();
string outputMessage = "";
try
{
while (rd.Read())
{
outputMessage += rd.GetValue(2) + "- " + rd.GetValue(3) + "\n";
}
}
catch (Exception x)
{
MessageBox.Show(x.Message.ToString());
}
rd.Close();
conn.Close();
MessageBox.Show(outputMessage);

Related

Retrieving data from a reader and saving it in a double variable

I'm making a project to issue tickets to a company.For this,I use a table to store the price of a ticket of adults and children.
In my program,I use a reader to retrieve these values in the table and save them to decimal variables.Here is the code.(adult-number of adult tickets,child-number of child tickets,adprice-price of an adult ticket,chprice-price of a child ticket.)
adult= Double.Parse(txtadult.Text);
child = Double.Parse(txtchild.Text);
con.Open();
String select_query_pri = "SELECT Adult,Child FROM Price WHERE No= 1 ";
cmd = new SqlCommand(select_query_pri, con);
SqlDataReader R = cmd.ExecuteReader();
while (R.Read())
{
adprice = R.GetDouble(0);
chprice = R.GetDouble(1);
}
con.Close();
tot = (adult * adprice) + (child * chprice);
txttotal.Text = tot.ToString();
Then I'm using another double variable to calculate the total of the tickets and then it is displayed in the program.But when the program is executed,an error appears saying "Specified cast is not valid".
What is the reason for this error?
Try using the following lines;
adprice = Convert.ToDouble(R[0]);
chprice = Convert.ToDouble(R[1]);

Insert Dataset Table records to SQLite table - in VB.NET

I've found this answer in C (Or C# maybe), but I don't really understand C. I'm a vb guy (and new to .net). Can anyone give me a hand in converting this to vb?
The concept appears to be exactly what I need:
I've got an Excel worksheet loaded to a dataset table.
I have an identical table in the SQLite db (column for column).
I want to save the imported Worksheet data in the dataset table to the empty SQLite table.
Here is the code from the link:
SQLiteConnection m_dbConnection;
void createDbAndTable()
{
SQLiteConnection.CreateFile("MyDatabase.sqlite");
m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite; Version=3;");
m_dbConnection.Open();
string sql = "create table myValues (name varchar(20), highScore int)";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
}
void fillTable(DataSet ds)
{
var dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
var name = dr["name"].ToString();
var score = Convert.ToInt32(dr["value"].ToString());
string sql = "insert into myValues (name, highScore) values ( '" + name + "'," + score + ")";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
}
m_dbConnection.Close();
}
Any help would be greatly appreciated!

I wrote an SQL SELECT statement that returns the entire table data rather then just the results that match my search

I have the following code that runs on a button click:
protected void Button2_Click(object sender, EventArgs e)
{
String str = "SELECT * " +
"FROM ConcernTicket INNER JOIN Employee " +
"ON ConcernTicket.EmployeeReportedToID = Employee.EmployeeId " +
"WHERE (Employee.FirstName LIKE '%' + #search2 + '%')";
SqlCommand xp = new SqlCommand(str, vid);
xp.Parameters.Add("#search2", SqlDbType.NVarChar).Value =
TextBox1.Text;
vid.Open();
xp.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = xp;
DataSet ds = new DataSet();
da.Fill(ds, "Employee.FirstName");
GridView2.DataSource = ds;
GridView2.DataBind();
vid.Close();
}
The problem I am facing is that the search runs with no errors but instead of just returning the results where the FirstName variable matches, it displays all current Concern Tickets. I am assuming it is a fairly simple fix with the SELECT statement, but for some reason I have not been able to figure out what is going wrong. I just started working with sql so I apologize that I am having such a silly issue, any help would be appreciated, thanks!
Check that TextBox1.Text is not empty. If it is empty, the query will be:
WHERE (Employee.FirstName LIKE '%%')";
Also check that #search2 is being replaced properly. The + operator is not what you would expect in MySQL. Perhaps this is what you're looking for:
"WHERE (Employee.FirstName LIKE '%#search2%')";
Hope that helps
your problem is not the SQL query. In fact you use ExecuteNonQuery() to extract select result. ExecuteNonQuery() just returns a single integer.Please use a code like this and let me know if the problem persists.
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
int i = 0;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
adapter.SelectCommand = new SqlCommand("Your SQL Statement Here", connection);
adapter.Fill(ds);
connection.Close();
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show(ds.Tables[0].Rows[1].ItemArray[1].ToString());
}
}

Visual Studio : IndexOutofRangeException

I am trying to access a table in Visual Studio 2012 and am using Oracle 11g as the back end.
This is my code part which is giving error:
comm = new OracleCommand();
comm.Connection = conn;
comm.CommandText = "select * from message where send_username='" + username + "' or r_username='"+username+"' order by id desc";
ds = new DataSet();
da = new OracleDataAdapter(comm.CommandText, conn);
da.Fill(ds, "message");
dt = ds.Tables["message"];
The same query when i run in SQL Command Prompt, it gives me 3 tuples as output but in this it is giving error
There is no row at position 1.
It is only giving one particular row as output no matter whatever else i do.
Any idea what I am doing wrong ??
if (ds.Tables.Count > 0 )
{
dt = ds.Tables["message"];
}
And
if (ds.Tables["message"].Rows.Count > 0)
{
}

c# - SqlReader of Read() not working

Problem: SqlReader of Read() not working
User Action:
enter their ID in a textbox and click a button
Program Action:
Select their name from database by given ID value
Then Print their name with HI! Message in RichTextBox or in Textbox
Error List:
No Error
Database:
Schema - dbo
Name - Sheet#Attendance
Here is my code:
private void swipe_button_Click(object sender, EventArgs e)
{
String ID_givenbyUSER = IDtxtBox.Text;
SqlConnection sqlConn = null;
sqlConn = new SqlConnection("Data Source=HOME-PC\\SQLEXPRESS;Initial Catalog=ABC_SchoolDB;Integrated Security=True");
sqlConn.Open();
SqlCommand cmd = new SqlCommand("select Student_Name from dbo.Sheet#Attendance where Serial_Id=" + " ' " + ID_givenbyUSER + " ' ", sqlConn);
SqlDataReader sqlReader = cmd.ExecuteReader();
richTxtBox.Clear();
richTxtBox.AppendText("Hi buddy "); //This line works
while (sqlReader.Read())
{
richTxtBox.AppendText("Hi buddy "); //But,Its not work
pwdbox.Text = (sqlReader["Student_Name"].ToString()); //Its not work too
}
if (sqlConn != null)
{
sqlConn.Close();
sqlConn = null;
}
}
}
I think your problem is here:
SqlCommand cmd = new SqlCommand("select Student_Name from dbo.Sheet#Attendance where Serial_Id=" + " ' " + ID_givenbyUSER + " ' ", sqlConn);
try this instead:
SqlCommand cmd = new SqlCommand("select Student_Name from dbo.Sheet#Attendance where Serial_Id='" + ID_givenbyUSER + "'", sqlConn);
Notice the part where you concatenate the single-quotes? It had spaces around them so your query would look like:
Where Serial_Id= ' Name '
The space in front of the user supplied value was probably causing your query to not return any rows.