Gridview not updating on pageload - c#

I have a gridview does not update on pageload. If you insert a value into the table, the page posts back and the gridview remains the same. All tho the record is inserted into the database. I'm fairly new to ADO.NET, any suggestions would be much appreciated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
public partial class Equip_DB : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataBind();
}
string cs = ConfigurationManager.ConnectionStrings["NIC"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand showAll = new SqlCommand("SELECT * FROM Equiptment", con);
SqlDataReader reads = showAll.ExecuteReader();
GridView1.DataSource = reads;
GridView1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["NIC"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
//INSERT INTO Equiptment VALUES ('2', 'Hammers', '24')
string query = "INSERT INTO Equiptment VALUES ('"+
equipAmount.Text +"', '"+
equipType.Text + "', '" +
DropDownList1.SelectedValue +"')";
AddContract.Visible = true;
SqlCommand cmd = new SqlCommand(query, con);
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch {
con.Close();
}
}
}

You are not binding gridview with updated content.
protected void Button1_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["NIC"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
//INSERT INTO Equiptment VALUES ('2', 'Hammers', '24')
string query = "INSERT INTO Equiptment VALUES ('"+
equipAmount.Text +"', '"+
equipType.Text + "', '" +
DropDownList1.SelectedValue +"')";
AddContract.Visible = true;
SqlCommand cmd = new SqlCommand(query, con);
try
{
con.Open();
cmd.ExecuteNonQuery();
con.Close();
//GRID LOAD CODE GOES HERE
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand showAll = new SqlCommand("SELECT * FROM Equiptment", con);
SqlDataReader reads = showAll.ExecuteReader();
GridView1.DataSource = reads;
GridView1.DataBind();
}
///////////////////////
}
catch {
con.Close();
}
}
}

Related

Generate Crystal Report Dynamically reading Store Procedure

I am developing a web form application. Here a Create a table named ReportConfig which contains ReportId, ReportCode, ReportName and Query column. An User will put there Store Procedure or select statement in the Query column.
Then, I made another Page named ReportDownload where an user will download a report based on the input he/she gave on the ReportConfig--> Query
Is it possible to create Crystal Report from every Store Procedure or Select statement from query column ?
Here is my ReportConfig page.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ReportManager
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadRecord();
}
}
SqlConnection con = new SqlConnection(#"Data Source=ANIK-IT\SQLEXPRESS;Initial Catalog=ReportManager;Persist Security Info=True;User ID=sa;Password=oLdViCtOrY2008");
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand comm = new SqlCommand("Insert into ReportConfig values ('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextArea1.InnerText + "')", con);
comm.ExecuteNonQuery();
con.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "alert('Successfully Inserted');", true);
LoadRecord();
}
void LoadRecord()
{
SqlCommand comm = new SqlCommand("Select * from ReportConfig", con);
SqlDataAdapter d = new SqlDataAdapter(comm);
DataTable dt = new DataTable();
d.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void Button2_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand comm = new SqlCommand("Update ReportConfig Set ReportName = '" + TextBox2.Text + "', Query = '" + TextArea1.InnerText + "' Where ReportCode= '" + TextBox1.Text + "' ", con);
comm.ExecuteNonQuery();
con.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "alert('Successfully Updated');", true);
LoadRecord();
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
}
protected void Button3_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand comm = new SqlCommand("Delete ReportConfig Where ReportCode = '" + TextBox1.Text + "' ", con);
comm.ExecuteNonQuery();
con.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "alert('Successfully Deleted');", true);
LoadRecord();
}
protected void Button4_Click(object sender, EventArgs e)
{
SqlCommand comm = new SqlCommand("Select * from ReportConfig Where ReportCode = '" + TextBox1.Text + "'", con);
SqlDataAdapter d = new SqlDataAdapter(comm);
DataTable dt = new DataTable();
d.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void Button5_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand comm = new SqlCommand("Select * from ReportConfig Where ReportCode = '" + TextBox1.Text + "'", con);
SqlDataReader r = comm.ExecuteReader();
while (r.Read())
{
TextBox2.Text = r.GetValue(2).ToString();
TextArea1.InnerText = r.GetValue(3).ToString();
}
con.Close();
}
}
}
Here is my ReportDownload page
using CrystalDecisions.CrystalReports.Engine;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ReportManager
{
public partial class ReportDownload : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(#"Data Source=ANIK-IT\SQLEXPRESS;Initial Catalog=ReportManager;Persist Security Info=True;User ID=sa;Password=oLdViCtOrY2008");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string com = "Select * from ReportConfig";
SqlDataAdapter adpt = new SqlDataAdapter(com, con);
DataTable dt = new DataTable();
adpt.Fill(dt);
DropDownList1.DataSource = dt;
DropDownList1.DataBind();
DropDownList1.DataTextField = "ReportName";
DropDownList1.DataValueField = "ReportId";
DropDownList1.DataBind();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string chk = DropDownList1.SelectedItem.Text;
string qur = String.Format("Select Query from ReportConfig Where ReportName ='" + chk + "'");
SqlCommand cmd = new SqlCommand(qur, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
string dsa = ds.Tables[0].Rows[0][0].ToString();
SqlCommand cmd1 = new SqlCommand(dsa, con);
SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
DataSet ds1 = new DataSet();
sda1.Fill(ds1);
ReportDocument crp = new ReportDocument();
crp.Load(Server.MapPath("ReportViewer.rpt"));
crp.SetDataSource(ds1.Tables["table"]);
CrystalReportViewer1.ReportSource = crp;
crp.ExportToHttpResponse(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, Response, false, "Report Config");
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(),"err_msg",
"alert('Invalid Store Procedure!)');",true);
}
}
}
}
also you can see what i do by downloading the project here
https://drive.google.com/file/d/1GsZSGFmHoINwyuorx3n-o0sH3U8cL2rS/view?usp=sharing

Showing oracle database values into gridview

Hi i've an oracle database with the table PROVA with 3 columns NOME, COGNOME, NUMTELEFONO.
i'm searching to update my gridview in c# with the value in contained into the table.
This is my code and into the method button1_Click() i need to show db values into my gridview c# app. Can someone help me with the code?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OracleClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Oracle.ManagedDataAccess;
namespace dbOracleForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label2_Click(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
String connectionString = "Data Source = (DESCRIPTION = "+
"(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))" +
"(CONNECT_DATA = " +
" (SERVER = DEDICATED) " +
" (SERVICE_NAME = orcl.home) " +
")"+
"); User Id = system;password = orcl;";
OracleConnection con = new OracleConnection();
con.ConnectionString = connectionString;
con.Open();
OracleCommand cmd = new OracleCommand();
cmd.CommandText = "SELECT NOME, COGNOME, NUMTELEFONO FROM PROVA ORDER BY COGNOME DESC";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataGridView1.DataSource(dt);
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
You can do like this
private void button1_Click(object sender, EventArgs e)
{
...
OracleCommand cmd = new OracleCommand();
cmd.CommandText = "SELECT NOME, COGNOME, NUMTELEFONO FROM PROVA ORDER BY COGNOME DESC";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataGridView1.DataSource(dt);//wrong
dataGridView1.DataSource= dt;//correct
}

SQL update failing to update database

This is my code behind for data update. But it is not updating in my database. Don't know why. Any suggestion pls.
I've check the database connection and it is working fine. I didn't declare the connection string using {..}.
Actually I didn't get any error message for the insert. I got an record update message. But in my database, it is not updating.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
namespace StudentDataDisplay2
{
public partial class Form1 : Form
{
SqlConnection conn = new SqlConnection(#"Data Source=localhost;Initial Catalog=TestData;Integrated Security=True");
public Form1()
{
InitializeComponent();
this.Text = "Student Data Display Form";
}
private void Form1_Load(object sender, EventArgs e)
{
}
public void display_data()
{
conn.Open();//establish connection
SqlCommand cmd = conn.CreateCommand();
//cmd.CommandType = CommandType.Text();
cmd.CommandText = "SELECT * from StudentDetails";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
conn.Close();
}
private void btnInsert_Click(object sender, EventArgs e)
{
conn.Open();//establish connection
SqlCommand cmd = conn.CreateCommand();
//cmd.CommandType = CommandType.Text();
cmd.CommandText = "INSERT INTO StudentDetails VALUES (#Name,#Subject)";
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = textBox1.Text; //add values in textbox1 and store in db
cmd.Parameters.Add("#Subject", SqlDbType.NVarChar).Value = textBox2.Text; //add values in textbox2 and store in db
cmd.ExecuteNonQuery();
conn.Close();
display_data();
MessageBox.Show("Record added");
}
private void btnDisplay_Click(object sender, EventArgs e)
{
display_data();
}
private void btnDelete_Click(object sender, EventArgs e)
{
conn.Open();//establish connection
SqlCommand cmd = conn.CreateCommand();
//cmd.CommandType = CommandType.Text();
cmd.CommandText = "DELETE FROM StudentDetails WHERE Name= #Name";
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = textBox1.Text; //add values in textbox1 and store in db
cmd.ExecuteNonQuery();
conn.Close();
display_data();
MessageBox.Show("Record deleted");
}
private void btnUpdate_Click(object sender, EventArgs e)
{
//conn.Open();//establish connection
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "UPDATE StudentDetails SET Name = #Name WHERE Subject = #Subject";
cmd.Parameters.AddWithValue("#Name", textBox1.Text);
cmd.Parameters.AddWithValue("#Subject", textBox2.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
display_data();
MessageBox.Show("Record updated!");
}
private void buttonSearch_Click(object sender, EventArgs e)
{
conn.Open();//establish connection
SqlCommand cmd = conn.CreateCommand();
//cmd.CommandType = CommandType.Text();
cmd.CommandText = "DELETE FROM StudentDetails WHERE Name= #Name";
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = textBox1.Text; //add values in textbox1 and store in db
cmd.ExecuteNonQuery();
conn.Close();
display_data();
MessageBox.Show("Search completed!");
}
}
}

Error when insert data from textbox to database

I have text and a button and when on submit, I am checking whether the database has any rows-if not then insert rows or else update them, but on submit its throwing an error saying incorrect syntax at "cmd.ExecuteNonQuery" in the else condition
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class CM : System.Web.UI.Page
{
DataSet ds = new DataSet();
SqlDataAdapter da;
SqlCommand cmd;
DataTable dt;
SqlConnection con = new SqlConnection("server =consulting76\\SQLEXPRESS; database = msdb; Integrated Security=True; MultipleActiveResultSets=True");
protected void Page_Load(object sender, EventArgs e)
{
da = new SqlDataAdapter("Select * from NOTESMAKER", con);
da.Fill(ds);
//dt = ds.Tables["NOTESMAKER"];
}
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
if (ds.Tables[0].Rows.Count == 0)
{
cmd = new SqlCommand("Insert into NOTESMAKER(NOTESMAKER) Values(#text1)",con);
cmd.Parameters.Add(new SqlParameter("#text1", SqlDbType.NText)).Value = TextBox1.Text;
da.InsertCommand = cmd;
cmd.ExecuteNonQuery();
}
else
{
cmd = new SqlCommand("Update NOTESMAKER set NOTESMAKER = #text1)",con);
cmd.Parameters.Add(new SqlParameter("#text1", SqlDbType.NText)).Value = TextBox1.Text;
da.UpdateCommand = cmd;
cmd.ExecuteNonQuery();
}
con.Close();
}
}
You are closing a bracket on this line, which is never opened:
cmd = new SqlCommand("Update NOTESMAKER set NOTESMAKER = #text1)",con);
Also, setting the InsertCommand and UpdateCommand properties of the data adapter isn't neccessary.

Encryption and Decryption failing while adding records

I am working with a simple program and now I got stuck with a problam that is encrypting and decrypting the password and storing them in the database. The logic I am working with is encrypting the password but it is not storing in the database, instead it is throwing an error showing below
System.Data.SqlClient.SqlException: Incorrect syntax near '='.
My Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
namespace WebApplication5
{
public partial class WebForm6 : System.Web.UI.Page
{
SqlConnection connection;
protected void Page_Load(object sender, EventArgs e)
{
connection = new SqlConnection(ConfigurationManager.ConnectionStrings["TestQueryConnectionString"].ConnectionString);
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["TestQueryConnectionString"].ConnectionString);
con1.Open();
SqlCommand cmd1 = new SqlCommand("select * from admin where USERNAME=#USERNAME and PASSWORD=#PASSWORD ", con1);
cmd1.Parameters.AddWithValue("#username", txtUserName.Text);
cmd1.Parameters.AddWithValue("#password", txtPassword.Text);
SqlDataReader dr = cmd1.ExecuteReader();
if (dr.HasRows)
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('userName is already availables')</script>");
}
else
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TestQueryConnectionString"].ConnectionString);
con.Open();
string strQuery = EncodePasswordToBase64("insert into admin( USERNAME,PASSWORD) values('" + txtUserName.Text + "','" + txtPassword.Text + "')");
connection = new SqlConnection(ConfigurationManager.ConnectionStrings["TestQueryConnectionString"].ConnectionString);
connection.Open();
SqlCommand cmd = new SqlCommand(strQuery, connection);
cmd.ExecuteNonQuery();
connection.Close();
Response.Redirect("login.aspx");
}
con1.Close();
}
public static string EncodePasswordToBase64(string password)
{
try
{
byte[] encData_byte = new byte[password.Length];
encData_byte = System.Text.Encoding.UTF8.GetBytes(password);
string encodedData = Convert.ToBase64String(encData_byte);
return encodedData;
}
catch (Exception ex)
{
throw new Exception("Error in base64Encode" + ex.Message);
}
}
}
}
Question is: What I am doing wrong here?
You are encoding the complete query instead you should only encode the password
string strQuery = EncodePasswordToBase64("insert ....
It should be:
string strQuery = "insert into admin( USERNAME,PASSWORD) values('" + txtUserName.Text +
"','" + EncodePasswordToBase64(txtPassword.Text) + "')");
You should use SqlParameter and make a Parameterized query instead o string concatenation
string strQuery = "insert into admin( USERNAME,PASSWORD) values(#pUserName, #pPassword)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("#pUserName", txtUserName.Text");
cmd.Parameters.AddWithValue("#pPassword", EncodePasswordToBase64(txtPassword.Text))

Categories