I am trying get value from GridView and decrement it that works. However, inserting to the database does not work. What's wrong?
protected void GridView1_SelectedIndexChanged1(object sender, EventArgs e)
{
m = GridView1.SelectedRow.Cells[5].Text;
int nm = Convert.ToInt32(m);
if (GridView1.SelectedRow.Cells[5].Text != "")
{
cn.Open();
nm--;
cmd.CommandText = ("INSERT INTO rezerwacje [miejsca] VALUES(#nm)");
//cmd.ExecuteNonQuery();
cmd.Clone();
cn.Close();
}
}
Seems you are not adding the parameter value
cmd.CommandText = ("INSERT INTO rezerwacje [miejsca] VALUES(#nm)");
cmd.Parameters.Add(new SqlParameter("nm", nm));
Related
I have a combobox that loads data from database but i got an error that you cannot set the selectedValue in a ListControl Although i have set the selectValue to a Primary key of a Table. But still getting error on runtime.. Here is the Code..
private void FormAddStudent_Load(object sender, EventArgs e)
{
//For combobox Campuse
cBoxCampus.DataSource = GetAllCampuses();
cBoxCampus.DisplayMember = "campus_name";
cBoxCampus.SelectedValue = "campus_id";
//Foe ComboBox Department
cBoxDepartment.DataSource = GetAllDepartment();
cBoxDepartment.DisplayMember = "depname";
cBoxDepartment.SelectedValue = "depid";
}
and this is the code behind Insert Button
private void btnInsert_Click(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["UMSdbConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT ISNULL(MAX(std_id),0)+1 FROM Student", con);
cmd.CommandType = CommandType.Text;
tbID.Text = cmd.ExecuteScalar().ToString();
{
using (SqlCommand cmd1 = new SqlCommand("INSERT INTO Student (std_id,std_name,std_f_name,std_mob,std_gender,std_cnic,std_campus,std_dep,std_address,std_batch,std_batch_year)VALUES(#std_id,#std_name,#std_f_name,#std_mob,#std_gender,#std_cnic,#std_campus,#std_dep,#std_address,#std_batch,#std_batch_year)VALUES(#campus_id,#campus_name)", con))
{
cmd1.CommandType = CommandType.Text;
cmd1.Parameters.AddWithValue("#std_id", tbID.Text);
cmd1.Parameters.AddWithValue("#std_name", tbName.Text);
cmd1.Parameters.AddWithValue("#std_f_name", tbFatherName.Text);
cmd1.Parameters.AddWithValue("#std_mob", tbMobNumber.Text);
cmd1.Parameters.AddWithValue("#std_gender", GetGender());
cmd1.Parameters.AddWithValue("#std_cnic", tbMobNumber.Text);
cmd1.Parameters.AddWithValue("#std_campus",(cBoxCampus.SelectedIndex == -1) ? 0: cBoxCampus.SelectedValue);
cmd1.Parameters.AddWithValue("#std_dep", (cBoxDepartment.SelectedIndex == -1) ? 0 : cBoxDepartment.SelectedValue);
cmd1.Parameters.AddWithValue("#std_address", tbAddress.Text);
cmd1.Parameters.AddWithValue("#std_batch", tbBatchNo.Text);
cmd1.Parameters.AddWithValue("#std_batch_year", tbBatchYear.Text);
cmd1.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Saved");
}
}
}
}
Replace
cBoxCampus.SelectedValue = "campus_id";
With ListControl.ValueMember Property
cBoxCampus.ValueMember = "campus_id";
Do similar operation for cBoxDepartment
I have problem with updating data.
Sample:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
string id = row.Cells[1].Text;
Response.Redirect("edit.aspx?id="+id);
}
after this code transition to another page with update cmd.
protected void Page_Load(object sender, EventArgs e)
{
DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
foreach (DataRowView drv in dv)
{
IDLBL.Text = drv["ID"].ToString();
Name.Text = drv["Name"].ToString();
SName.Text = drv["SecondName"].ToString();
Ocenka.Text = drv["Graduate"].ToString();
Klass.Text = drv["Class"].ToString();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ARM_TSPConnectionString"].ConnectionString);
con.Open();
string upd = "UPDATE Info SET Name=#Name, SecondName=#SecondName, Graduate=#Graduate, Class=#Class WHERE ID=#ID";
SqlCommand cmd = new SqlCommand(upd, con);
cmd.Parameters.AddWithValue("#ID", IDLBL.Text);
cmd.Parameters.AddWithValue("#SecondName", SName.Text);
cmd.Parameters.AddWithValue("#Graduate", Ocenka.SelectedValue);
cmd.Parameters.AddWithValue("#Class", Klass.SelectedValue);
cmd.Parameters.AddWithValue("#Name", Name.Text);
cmd.ExecuteNonQuery();
Response.Redirect("main.aspx");
}
I clicked button, and was redirected to main page. But nothing else, update doesn't work. :(
where do I have a problem?
I don't really know where is the problem, but for sure you need to refactor your update statement using the IDisposable capabilities of the connection object, it shoul look like this:
using (SqlConnection connection = new SqlConnection(
ConfigurationManager.ConnectionStrings["ARM_TSPConnectionString"].ConnectionString))
{
string upd = "UPDATE Info SET Name=#Name, SecondName=#SecondName, Graduate=#Graduate, Class=#Class WHERE ID=#ID";
SqlCommand cmd = new SqlCommand(upd, connection);
cmd.Parameters.AddWithValue("#ID", IDLBL.Text);
cmd.Parameters.AddWithValue("#SecondName", SName.Text);
cmd.Parameters.AddWithValue("#Graduate", Ocenka.SelectedValue);
cmd.Parameters.AddWithValue("#Class", Klass.SelectedValue);
cmd.Parameters.AddWithValue("#Name", Name.Text);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
Your update sql query looks fine:
con.Open();
com.ExecuteNonQuery();
con.Close();
that is try using this function instead and debug it to see if there is a sql exception thrown.
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ARM_TSPConnectionString"].ConnectionString);
string upd = "UPDATE Info SET Name=#Name, SecondName=#SecondName, Graduate=#Graduate, Class=#Class WHERE ID=#ID";
SqlCommand cmd = new SqlCommand(upd, con);
cmd.Parameters.AddWithValue("#ID", IDLBL.Text);
cmd.Parameters.AddWithValue("#SecondName", SName.Text);
cmd.Parameters.AddWithValue("#Graduate", Ocenka.SelectedValue);
cmd.Parameters.AddWithValue("#Class", Klass.SelectedValue);
cmd.Parameters.AddWithValue("#Name", Name.Text);
con.Open();
com.ExecuteNonQuery();
con.Close();
Response.Redirect("main.aspx");
}
catch (SqlException e)
{
}
}
UPDATE: Think I've realised why it's not working for you... you have a column called class... but class in sql server is a reserved keyword... so you must put square brackets around it ... like so
Edited the escaping (made a mistake as pointed out by Hans in the comment below)
string upd = "UPDATE Info SET Name=#Name, SecondName=#SecondName, Graduate=#Graduate, [Class]=#Class WHERE ID=#ID";
The problem was found.Just add in Page_Load if(!isPostBack)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
foreach (DataRowView drv in dv)
{
IDLBL.Text = drv["ID"].ToString();
Name.Text = drv["Name"].ToString();
SName.Text = drv["SecondName"].ToString();
Ocenka.Text = drv["Graduate"].ToString();
Klass.Text = drv["Class"].ToString();
}
}
Now, all working good.
I'm trying to display multiple rows from a query into a literal in asp.net c#. Here is my code for doing so:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["RaiseFantasyLeagueConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("[dbo].[GetUsersLeagues]", conn);
cmd.CommandType = CommandType.StoredProcedure;
string userId = Membership.GetUser().ProviderUserKey.ToString();
SqlParameter userIDParam = new SqlParameter("#userId", userId);
cmd.Parameters.Add(userIDParam);
conn.Open();
SqlDataReader dReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (dReader.Read())
{
usersLeagues.Text = (dReader["LeagueName"].ToString());
}
dReader.Close();
conn.Close();
}
My issue is that the literal is only displaying one of the rows, i've tried this with a list box and all rows were displayed.
Any suggestions?
Thanks in advance!
You are replacing the value of the Text property on each iteration:
while (dReader.Read())
{
usersLeagues.Text = (dReader["LeagueName"].ToString());
}
Instead of that, you need to concatenate the values on each iteration:
while (dReader.Read())
{
usersLeagues.Text += (dReader["LeagueName"].ToString()) + Environment.NewLine;
}
In the above example, using += causes an append to the current value of usersLeagues.Text, instead of a replacement.
Access 2003 db
Field Name Data Type
CriminalOffence Text
VS 2010 C#
Using a groupbox, I can store data from radiobutton into my db. I have databinded both groupbox and radiobuttons to my db. When I use my nativgation buttons I see the data that has been stored where the groupbox text is. So the problem is I don't know how to properly retrieve data for the radiobutton. Retrieving data from textbox and combox is showing as it should be. Also when I want to insert new data the radiobutton does not get cleared. So...
I have two radiobuttons named, 1) rBYes 2) rBNo
I have the following method for inserting record...
private void btnInsert_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand(#"INSERT INTO Table1
(ID, AgeGroup, Gender, CriminalOffence)
VALUES(#txtID, #AcBAG, #cBGender, #CriminalOffence)", myCon);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#ID", txtID.Text);
cmd.Parameters.AddWithValue("#AgeGroup", cBAG.Text);
cmd.Parameters.AddWithValue("#Gender", cBGender.Text);
string str = "";
if (rBYes.Checked)
{
str = "Yes";
}
if (rBNo.Checked)
{
str = "No";
}
cmd.Parameters.AddWithValue("#CriminalOffence", SqlDbType.NVarChar).Value =
str;
}
And a method for creating a new record
private void btnNew_Click(object sender, EventArgs e)
{
txtID.Text = "";
cBAG.Text = "";
cBGender.Text = "";
rBYes.Text = "";
rBNo.Text = "";
}
An example of navigation button..
private void btnNextRec_Click(object sender, EventArgs e)
{
this.table1BindingSource.MoveNext();
}
ConnectionString...
myCon = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\..
\Database1.mdb");
Please can someone help me here, thanks in advance
Parameter names must match the parameters in the SQL insert statement.
private void btnInsert_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand(#"INSERT INTO Table1
(ID, AgeGroup, Gender, CriminalOffence)
VALUES(#ID, #AgeGroup, #Gender, #CriminalOffence)", myCon);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#ID", txtID.Text);
cmd.Parameters.AddWithValue("#AgeGroup", cbAG.Text);
cmd.Parameters.AddWithValue("#Gender", cbGender.Text);
cmd.Parameters.AddWithValue("#CriminalOffence", ((rBYes.Checked)? "Yes":"No"));
myCon.Open();
cmd.ExecuteNonQuery();
myCon.Close();
}
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.