I got exception handling at ExexuteNonQuery at gridview in asp.net - asp.net

Label lb = (Label)GridView1.Rows[e.RowIndex].FindControl("Label6");
TextBox tx1 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox1");
TextBox tx2 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox2");
mycon.Open();
SqlCommand myupdatecommand = new SqlCommand("update Users set(user_name,user_surname) values('"+tx1.Text+"','"+tx2.Text+"') where user_id='"+lb.Text+"'", mycon);
myupdatecommand.ExecuteNonQuery();
GridView1.EditIndex = -1;
GridView1.DataBind();
Thanks!

first update statement is not correct, secondly please use SQL Parameters in order to avoid the SQL Injection.
SqlCommand cmd= new SqlCommand("update Users set user_name=#userName,user_surname=#userSurName where user_id=#userID", mycon);
cmd.Parameters.AddWithValue("#userName",yournameTextBox.Text);
cmd.Parameters.AddWithValue("#userSurName",yourSurnnameTextBox.Text);
cmd.Parameters.AddWithValue("#userID",yourID);

Related

Saving checked status from a checkbox into the database in asp.net

I'm working on a online test application in asp.net and i'm finding trouble in saving the checked answer status back to database, i.e once i click on next button in my aspx page these 2 things should happen
1)It should capture the currently checked option and add the value for that particular option as true into my database IS_Marked column.
2)It also should pull out the next set of question and Options
The latter is fine but i'm not getting any clue about how to save the checkd answer back into database
My aspx has 4 check boxes
and my next button click event is as follows,
protected void BtnNext_Click(object sender, EventArgs e)
{
if (qid == maxid)//checks whether current que id is equal to last que id in DB
{
BtnNext.Enabled = false; //if its last que then next button is disabled
}
else
{
BtnPrevious.Enabled = true; // if not last question next button is enabled
QuestionSet q = new QuestionSet(); //Question set is an entity to hold que text and options list
StudentB b = new StudentB(); //object of my business class
q = b.GetQuestion(1, 1, qid, 'N', 0);//passing student id, test id, question id, action taken, i.e button clicked(prev, next, last, first) and selected question(i.e any question that is present)
qid = Convert.ToInt32(q.Question_Id);
LblQStn.Text = q.Question_Text;
CheckBox1.Text = q.Options[0].Option_Text;//talking to business and model layer and getting que and ans from database and giving to checkboxes
CheckBox2.Text = q.Options[1].Option_Text;
CheckBox3.Text = q.Options[2].Option_Text;
CheckBox4.Text = q.Options[3].Option_Text;
}
}
now when he checks any answer i need to save its status as marked into the database
Any solution is highly appreciated,
thanks in advance
Well first you need to set up the connection to database. example:
//sqlString is your connectionstring//
dbconn = New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("sqlString"))
dbconn.Open()
strsql = "INSERT INTO IS_Marked ([Mark]) VALUES ('" + Bedrijf + "')"
dbcomm = New SqlCommand(strsql, dbconn)
dbcomm.ExecuteNonQuery()
dbconn.Close()
This will be your basic sql command.
As you can see I ues ([yourvalue]) that what we are going to do next.
Dim dbconn As SqlConnection
Dim dbcomm As SqlCommand
Dim strsql, Checked_Mark As String
Mark = YourCheckBox.CheckedValue
So your final result will be like this:
Dim dbconn As SqlConnection
Dim dbcomm As SqlCommand
Dim strsql, Mark As String
Mark = YourCheckBox.CheckedValue
dbconn = New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("sqlString"))
dbconn.Open()
strsql = "INSERT INTO IS_Marked ([Mark]) VALUES ('" + Bedrijf + "')"
dbcomm = New SqlCommand(strsql, dbconn)
dbcomm.ExecuteNonQuery()
dbconn.Close()

crystal reports giving Database logon failed or asking for credentials

i have tried almost everything I could. I have a web app in ASP.net with c#. I am fetching data from the database tables and adding it to dataset. Then I set this dataset as the source to the report. My code is as following.
con.ConnectionString = ConfigurationManager.ConnectionStrings["familyConnectionString"].ConnectionString;
SqlDataAdapter sda = new SqlDataAdapter("select uid, member_name, gender, dob from family where uid='"+uid+"'", con);
DataSet1 myds = new DataSet1();
sda.Fill(myds, "family");
SqlDataAdapter sda1 = new SqlDataAdapter("select id from birth_certificates where p_id='"+uid+"'", con);
sda1.Fill(myds, "birth_certificates");
ReportDocument rpt = new ReportDocument();
rpt.Load(Server.MapPath("birth_certi_report.rpt"));
rpt.Refresh();
rpt.SetDataSource(myds);
rpt.SetDatabaseLogon("","",#".\sqlexpress","project2");
CrystalReportViewer1.ReportSource = rpt;
CrystalReportViewer1.DataBind();
CrystalReportViewer1.Visible = true;
CrystalReportViewer1.RefreshReport();
I am using integrated security so I left username and password blank. Please help.
Please Note that the above code is written inside a DropDown_selectedIndexChanged() event. I tried adding it to the page_load but it didn't work.
If you are not worried about authentication ,then do it this way.Create an instance of your crystal report and set its data source.Thats all you need to do and it works.
*Make sure the crystal report is within your solution.
con.ConnectionString = ConfigurationManager.ConnectionStrings["familyConnectionString"].ConnectionString;
// the magic
birth_certi_report myreport = new birth_certi_report();
DataSet1 myds = new DataSet1();
SqlDataAdapter sda1 = new SqlDataAdapter("select id from birth_certificates where p_id='"+uid+"'", con);
sda1.Fill(myds, "birth_certificates");
myreport.SetDataSource(myds);
crystalReportViewer1.ReportSource = myreport;
birth_certi_report myreport = new birth_certi_report();
in this line you have mentioned that birth_certi_report is crystal report. my crystal report name is applicationreport but it shows an error.
Dim myreport As New appilcationreport
error is TYPE IS NOT DEFINED

system.data.common.datarecordinternal error in .net

// Dropdown data for module_drp
SqlConnection mod_conn = new SqlConnection(#"Data Source=4D\SQLEXPRESS;Initial Catalog=tracker;Integrated Security=True");
mod_conn.Open();
string selectcmd = #"select testmodule.names from dbo.testmodule";
SqlCommand cd1 = new SqlCommand(selectcmd,mod_conn);
//cd1.ExecuteNonQuery();
SqlDataReader dr1 = cd1.ExecuteReader();
module_drp.DataSource = dr1;
module_drp.DataBind();
mod_conn.Close();
After compiling am getting an error - system.data.common.datarecordinternal
You should set the DataTextField property for the module_drp in the .aspx file with -
DataTextField="testmodule.names"
Hope this helps :).

Why SQLCommandBuider not DELETING?

In the following code UPDATE is working but DELETE is not working. When I DELETE row it delete it and GridView1 does not show it but database still has it. customers has PrimaryKey.
using (SqlConnection connection = new SqlConnection(conString))
{
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand("select * from customers", connection);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
connection.Open();
DataTable customers = new DataTable();
adapter.Fill(customers);
// code to modify data in DataTable here
customers.Rows.RemoveAt(rowIndex);
GridView1.EditIndex = -1;
GridView1.DataSource = customers;
GridView1.DataBind();
adapter.Update(customers);
You don't want to remove the row from the DataTable but delete it.
The DataRow's DataRowState must be modified to deleted, then the DataAdapter knows that it must delete it in the datasource.
Following will delete it:
customers.Rows(rowIndex).delete();//now DataRow's DataRowState is Deleted
adapter.Update(customers); // now it's actually deleted
Futher informations: MSDN How to: Delete Rows in a DataTable
By the way, following would prevent the DataRow to be deleted, if you've changed your mind:
customers.Rows(rowIndex).RejectChanges();
The RowState will change back to Unchanged.
This works either for the DataRow or for the whole DataTable.

Grid view with Datasource control

Sir,
Im doing a project in asp.net 4.0 with c#.I my project i want to display datas from the database to the grid view using Data Source Control. But while doing it im getting an eror called "The DataSourceID of 'GridView1' must be the ID of a control of type IDataSource. A control with ID 'System.Web.UI.WebControls.SqlDataSource' could not be found.".
My code is also givren below.
SqlCommand cmd = new SqlCommand("SPS_LeaveBalanceReport_DSO", Connect.con());
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ReportMonth", SqlDbType.NVarChar).Value =
SelectMonthDropDown.SelectedValue.ToString();
cmd.Parameters.Add("#ReportYear", SqlDbType.NVarChar).Value =
SelectYearDropDown.SelectedItem.Text.ToString();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "tab");
GridView1.DataSourceID = SqlDataSource1.ToString();
GridView1.DataBind();
Please help me with error.,thanks In Advance.,
change
GridView1.DataSourceID = SqlDataSource1.ToString();
to
GridView1.DataSourceID = SqlDataSource1.ID;
The problem is no where in your cod ejust replace the line
GridView1.DataSourceID = SqlDataSource1.ToString();
with
GridView1.DataSource=ds;
it will work

Resources