Inserting selected data using checkbox from gridview - c#

When I select the in the gridview using checkbox, I want it to insert the data into the database, but it is not adding it. My code is below, please see where I am going wrong.
public partial class HomeTeamCheckList : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
LiveGameReporting Window
SubmitLineUp.Attributes.Add("onclick", "PassValues();");
SubmitLineUp.Text = "Submit " + Session["HomeTeam"] + "'s Line Up";
}
protected void SubmitLineUp_Click(object sender, EventArgs e)
{
String GameID = string.Empty;
String Name = string.Empty;
String Number = string.Empty;
int GKGVCount = GoalKeeperGridView.Rows.Count;
foreach (GridViewRow gkrow in GoalKeeperGridView.Rows)
{
GameID = (String)Session["GameID"];
Number = gkrow.Cells[0].Text;
Name = gkrow.Cells[1].Text;
SqlConnection connection = new SqlConnection(("Data Source=ROBEL-HP;Initial Catalog=RocoSportsDB;Integrated Security=True"));
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandText = #"INSERT INTO HTLineUp (GameID, HomeTeamLineUpNo, HomeTeamLineUpName) VALUES (#GameID,#Number,#Name)";
cmd.Parameters.AddWithValue("#GameID", GameID);
cmd.Parameters.AddWithValue("#Number", Number);
cmd.Parameters.AddWithValue("#Name", Name);
cmd.ExecuteNonQuery();
}
}
}
}

Two thoughts:
Use a try-catch to see if you're getting any SQL errors.
Check the return value of the cmd.ExecuteNonQuery(); to see if any rows were actually affected / inserted.
Like this:
SqlConnection connection = new SqlConnection(("Data Source=ROBEL-HP;Initial Catalog=RocoSportsDB;Integrated Security=True"));
try
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandText = #"INSERT INTO HTLineUp (GameID, HomeTeamLineUpNo, HomeTeamLineUpName) VALUES (#GameID,#Number,#Name)";
cmd.Parameters.AddWithValue("#GameID", GameID);
cmd.Parameters.AddWithValue("#Number", Number);
cmd.Parameters.AddWithValue("#Name", Name);
// use a debugger to see if any rows were actually affected / inserted
int rowsAffected = cmd.ExecuteNonQuery();
}
catch(SQLException error)
{
// Use a debugger to see if you are getting an error on execution
string errorText = error.message;
}
Your query string looks ok, so it could be a permissions error. But the steps above will help you track it down.

Related

user selection Combobox then to Labels according to database MS Access c#

i have the following code below and what im trying to do is on the comboBox there is "ID" from my database and this ID represents every survey detail that Admin used to create so when the user goes to view the survey they click on the survey number in comboBox and the labels will change according to the database. I tried it with the below code but unfortunatley all it seems to do is grab a random one, if someone could help that would be amazing. It doesnt have to be like below, just as long as it works,
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
con.Open();
string query = "SELECT * FROM tbl_newsurvey ";
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = query;
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string name = reader["txtname"].ToString();
lblname.Text = name;
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
You can try this to search data from database using Combobox
I use parameterized query to avoid SQL Injection
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
con.Open();
string query = "SELECT * FROM tbl_newsurvey WHERE [ColumnName] = #ComboBoxValue";
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#ComboBoxValue", comboBox1.SelectedIndex.ToString())
OleDbDataReader reader = cmd.ExecuteReader();
if (reader.Read() == true)
{
string name = reader["txtname"].ToString();
lblname.Text = name;
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}

Retrieve Auto Increment ID from SQL Database after Insert Statement

Below here is my code to Retrieve Auto Increment ID After Inserting data into database.
However, I am getting Auto Increment ID before Inserting data into database.
How can I get auto increment ID after insert into database?
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
RetrievePRReqID();
}
}
//Retrieve ID method
private void RetrievePRReqID()
{
try
{
string query = "Select IDENT_CURRENT('tblPRRequest')";
if (sqlCon.State == ConnectionState.Closed)
{
sqlCon.Open();
}
SqlCommand cmd = new SqlCommand(query, sqlCon);
SqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
int value = int.Parse(reader[0].ToString()) ;
txt_PRNO.Text = value.ToString();
}
}
catch(Exception)
{
throw;
}
finally
{
if(con.State == ConnectionState.Open)
{
con.Close();
}
}
}
//Request button Method
protected void btn_Request(object sender, EventArgs e)
{
string insertCmd = "INSERT INTO tblPRRequest (RequestTo,RequestFrom,RequestedByName) " +
"VALUES (#RequestTo,#RequestFrom,#RequestedByName)";
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
using (SqlCommand sqlcmd = new SqlCommand(insertCmd, conn))
{
sqlcmd.Parameters.Clear();
SqlCommand sqlCmd = new SqlCommand(insertCmd, sqlCon);
sqlcmd.Parameters.AddWithValue("#RequestTo", lblPurchasingDept.Text);
sqlcmd.Parameters.AddWithValue("#RequestFrom", ddlDept.SelectedItem.Text);
sqlcmd.Parameters.AddWithValue("#RequestedByName", SUserName.Text);
sqlcmd.ExecuteNonQuery();
}
}
***//After Insert into the table, I want to retrieve latest generated Auto Increment ID in here.***
}
By referring sample answer from #Mx.Wolf, I modified a bit to get the right answer, below here is the codes that is working :
protected void btn_Request(object sender, EventArgs e)
{
object id ;
string insertCmd = "INSERT INTO tblPRRequest (RequestTo,RequestFrom,RequestedByName) " +
"output inserted.PRReqID " +
"VALUES (#RequestTo,#RequestFrom,#RequestedByName)";
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
using (SqlCommand sqlcmd = new SqlCommand(insertCmd, conn))
{
sqlcmd.Parameters.AddWithValue("#RequestTo", lblPurchasingDept.Text);
sqlcmd.Parameters.AddWithValue("#RequestFrom", ddlDept.SelectedItem.Text);
sqlcmd.Parameters.AddWithValue("#RequestedByName", SUserName.Text);
id = sqlcmd.ExecuteScalar(); //the result is of Object type, cast it safely
}
}
Debug.WriteLine(id.ToString()); // Access it like this
As stated in SQL Server documentation
https://learn.microsoft.com/en-us/sql/t-sql/queries/output-clause-transact-sql?view=sql-server-ver15
The OUTPUT clause may be useful to retrieve the value of identity or computed columns after an INSERT or UPDATE operation.
You have to change your SQL statement
INSERT INTO tblPRRequest (RequestTo,RequestFrom,RequestedByName)
OUTPUT inserted.ID
-------^^^^^^^^_^^
VALUES (#RequestTo,#RequestFrom,#RequestedByName)
and now you can use ExecuteScalar to get the inserted value
protected void btn_Request(object sender, EventArgs e)
{
int id= 0;
string insertCmd = "INSERT INTO tblPRRequest (RequestTo,RequestFrom,RequestedByName) " +
"output inserted.ID" +
"VALUES (#RequestTo,#RequestFrom,#RequestedByName)";
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
using (SqlCommand sqlcmd = new SqlCommand(insertCmd, conn))
{
sqlcmd.Parameters.AddWithValue("#RequestTo", lblPurchasingDept.Text);
sqlcmd.Parameters.AddWithValue("#RequestFrom", ddlDept.SelectedItem.Text);
sqlcmd.Parameters.AddWithValue("#RequestedByName", SUserName.Text);
id = (int)sqlcmd.ExecuteScalar(); //the result is of Object type, cast it safely
}
}
Debug.WriteLine(id.ToString()); // Access it like this
}
Try this:
protected void btn_Request(object sender, EventArgs e)
{
string insertCmd = "INSERT INTO tblPRRequest (RequestTo,RequestFrom,RequestedByName) " +
"VALUES (#RequestTo,#RequestFrom,#RequestedByName)";
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
using (SqlCommand sqlcmd = new SqlCommand(insertCmd, conn))
{
sqlcmd.Parameters.Clear();
SqlCommand sqlCmd = new SqlCommand(insertCmd, sqlCon);
sqlcmd.Parameters.AddWithValue("#RequestTo", lblPurchasingDept.Text);
sqlcmd.Parameters.AddWithValue("#RequestFrom", ddlDept.SelectedItem.Text);
sqlcmd.Parameters.AddWithValue("#RequestedByName", SUserName.Text);
sqlcmd.Parameters.Add("#ID", SqlDbType.Int).Direction = ParameterDirection.Output;
sqlcmd.ExecuteNonQuery();
}
}
***//After Insert into the table, I want to retrieve latest generated Auto Increment ID in here.***
sqlcmd.Parameters["#ID"].value; // Access it like this
}
In case you can chage the ExecuteNonQuery to ExecuteScalar, then it would be even easier: What is the difference between ExecuteScalar, ExecuteReader and ExecuteNonQuery?

Function that is supposed to insert a list of objects into a database only inserts one of the objects n times

I've been trying to create a function that will set up an order for all the items that are lacking in my inventory.
RequiredStockForAllOrders basically assigns a value to each object in stockItems which lets me know how many items I need to order.
I checked with a messagebox which does the change in values (both ID and quantity) but when I run the loop that is supposed to insert each product with its respective quantity I only insert 1 product n times where n is the amount of items in the list.
private void AddAllRequiredItems_Click(object sender, EventArgs e)
{
var stockItems = new List<MyData>();
//MyData is an object with a productID int and a productQuantity int
RequiredStockForAllOrders(stockItems);
//determining the quantity required for each item
OleDbConnection con = new OleDbConnection(DatabaseConnectionString);
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
con.Open();
string sql2 = "INSERT INTO restockingDetails(RestockingID,ProductID,Quantity,Shop_ID) values (#restockingID,#productID,#quantity,#shop_id)";
cmd.CommandText = sql2;
int i = 0;
while (i < stockItems.Count)
{
try
{
MessageBox.Show(stockItems[i].productId.ToString()); //For testing
cmd.Parameters.AddWithValue("#restockingID", restockingOrder);
cmd.Parameters.AddWithValue("#productID", stockItems[i].productId);
cmd.Parameters.AddWithValue("#quantity", stockItems[i].productQuantity);
cmd.Parameters.AddWithValue("#shop_id", shopIDGlobal);
cmd.ExecuteNonQuery();
MessageBox.Show(" Item added to list"); //for testing
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
i = i + 1;
}
con.Close()
}
Just add this line before adding the parameters
MessageBox.Show(stockItems[i].productId.ToString()); //For testing
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#restockingID", restockingOrder);
You actual code continues to add parameters to the command collection, but the query uses only the first four. With other providers this code will result in an error (too many parameters) but OleDb is somebit limited in this point. Probably because it doesn't recognize parameters by their name, but by their position
A better approach could be to define the parameters just once and then updating their values inside the loop
private void AddAllRequiredItems_Click(object sender, EventArgs e)
{
var stockItems = new List<MyData>();
RequiredStockForAllOrders(stockItems);
string sql2 = "INSERT INTO restockingDetails(RestockingID,ProductID,Quantity,Shop_ID) values (#restockingID,#productID,#quantity,#shop_id)";
using(OleDbConnection con = new OleDbConnection(DatabaseConnectionString))
using(OleDbCommand cmd = new OleDbCommand(sql2, con))
{
con.Open();
cmd.Parameters.Add("#restockingID", OleDbType.Integer);
cmd.Parameters.Add("#productID", OleDbType.Integer);
cmd.Parameters.Add("#quantity", OleDbType.Integer);
cmd.Parameters.Add("#shop_id", OleDbType.Integer);
foreach(MyData item in stockItems)
{
try
{
cmd.Parameters["#restockingID"].Value = restockingOrder;
cmd.Parameters["#productID"].Value = item.productId;
cmd.Parameters["#quantity"].Value = item.productQuantity;
cmd.Parameters["#shop_id"].Value = shopIDGlobal;
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
create the command into the while loop :
OleDbConnection con = new OleDbConnection(DatabaseConnectionString);
OleDbCommand cmd;
string sql2 = "INSERT INTO restockingDetails(RestockingID,ProductID,Quantity,Shop_ID) values (#restockingID,#productID,#quantity,#shop_id)";
int i = 0;
while (i < stockItems.Count)
{
try
{
MessageBox.Show(stockItems[i].productId.ToString()); //For testing
cmd = new OleDbCommand();
cmd.Connection = con;
con.Open();
cmd.CommandText = sql2;
cmd.Parameters.AddWithValue("#restockingID", restockingOrder);
cmd.Parameters.AddWithValue("#productID", stockItems[i].productId);
cmd.Parameters.AddWithValue("#quantity", stockItems[i].productQuantity);
cmd.Parameters.AddWithValue("#shop_id", shopIDGlobal);
cmd.ExecuteNonQuery();
MessageBox.Show(" Item added to list"); //for testing
con.Close()
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
i = i + 1;
}

how to search table through textbox?

I have piece of query that search database from text box.
My question is how can insert search result column by column to separated text box, I mean each column go to one textbox.
private void searchbtn_Click(object sender, EventArgs e)
{
SqlCeConnection con = new SqlCeConnection(#"Data Source=C:\Users\hry\Documents\Visual Studio 2010\Projects\Kargozini\Kargozini\khadamat.sdf");
try
{
con.Open();
string SearchQuerry = "SELECT ID, radif, Name, Type, Description, Price FROM Users WHERE ID = '"+searchtxt.Text+"'" ;
SqlCeCommand com = new SqlCeCommand(SearchQuerry,con);
com.ExecuteNonQuery();
con.Close();
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.Message);
}
}
Try this :
private void searchbtn_Click(object sender, EventArgs e)
{
SqlConnection sql = new SqlConnection("Your String Connection");
SqlDataAdapter adapter = new SqlDataAdapter(#"Select Name, FileName From Table Where Name Like #Name", sql);
adapter.SelectCommand.Parameters.AddWithValue("#Name", string.Format("%{0}%", textBox1.Text));
}
I assume that, your search will return only one row.
You can use datareader to achieve that. I modified your function with below code:
private void searchbtn_Click(object sender, EventArgs e)
{
SqlCeConnection con = new SqlCeConnection(#"Data Source=C:\Users\hry\Documents\Visual Studio 2010\Projects\Kargozini\Kargozini\khadamat.sdf");
try
{
con.Open();
string SearchQuerry = "SELECT ID, radif, Name, Type, Description, Price FROM Users WHERE ID = '"+searchtxt.Text+"'" ;
SqlCeCommand com = new SqlCeCommand(SearchQuerry,con);
SqlCeDataReader sqlReader = com.ExecuteReader();
while (sqlReader.Read())
{
txtID.text = sqlReader.GetValue(0).ToString();
txtRadif.text = sqlReader.GetValue(1).ToString();
txtName.text = sqlReader.GetValue(2).ToString();
}
sqlReader.Close();
com.Dispose();
con.Close();
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.Message);
}
}
Note: Your code is vulnerable to sqlinjection. Learn things to avoid it.

C# ADO.NET: check for existing index

I have the following code and I want to show an error message if the id is not found in the table can any body help?
private void button4_Click(object sender, EventArgs e)
{
conn = new MySqlConnection(cs);
string sql = "select * from question where id=#id;";
MySqlCommand cmd = new MySqlCommand(sql, conn);
conn.Open();
cmd.Prepare();
cmd.Parameters.AddWithValue("#id", int.Parse(textBox1.Text));
MySqlDataReader rd = cmd.ExecuteReader();
string res = "";
while (rd.Read())
{
if (rd.HasRows==true)
{
res = string.Format("id={0} pid={1} question={2}", rd.GetInt32(0), rd.GetInt32(1), rd.GetString(2));
MessageBox.Show("found" + "\n" + res);
}
MessageBox.Show(" id not found");
}
You need to check for has rows before to start iterating the reader.
if (rd.HasRows==true)
{
while (rd.Read())
{
// Do something here
}
}
else
{
// Show message here
}

Categories

Resources