Showing oracle database values into gridview - c#

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
}

Related

Invalid postback or callback argument when I try to input another search in my textbox using ASP.net

I try to create a Search Web form that you can type in a textbox for search and display it to the GridView.
This is functioning if it is a first-time search but when I try to type another data it displays an error.
Invalid postback or callback argument.
What should I replace or edit in 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;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Services;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text.RegularExpressions;
namespace BISCOM_SGS
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Focus();
}
private void BindData(string fullname)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM tbl_FrmApproval WHERE fullname = #fullname", con))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
cmd.Parameters.AddWithValue("#fullname", fullname);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
con.Close();
}
}
}
protected void SearchCustomer(object sender, EventArgs e)
{
this.BindData(this.TextBox1.Text.Trim());
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData(this.TextBox1.Text);
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData(this.TextBox1.Text);
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string rec_id = ((Label)GridView1.Rows[e.RowIndex].FindControl("rec_id")).Text;
string fullname = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtfullname")).Text;
string address = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtaddress")).Text;
string contact_no = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtcontact_no")).Text;
string gender = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtgender")).Text;
string age = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtage")).Text;
string company_name = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtcompanyname")).Text;
string company_address = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtcompanyaddress")).Text;
string discription = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtdiscription")).Text;
string dateofvisit = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtdateofvisit")).Text;
string visitorsID = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtvisitorsID")).Text;
string status = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtstatus")).Text;
string types = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txttypes")).Text;
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(constr, con))
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update tbl_FrmApproval set visitorsID=#visitorsID,status=#status,types=#types " +
"where fullname=#fullname";
cmd.Parameters.Add("#rec_id", SqlDbType.VarChar).Value = rec_id;
cmd.Parameters.Add("#fullname", SqlDbType.VarChar).Value = fullname;
cmd.Parameters.Add("#address", SqlDbType.VarChar).Value = address;
cmd.Parameters.Add("#contact_no", SqlDbType.VarChar).Value = contact_no;
cmd.Parameters.Add("#gender", SqlDbType.VarChar).Value = gender;
cmd.Parameters.Add("#age", SqlDbType.VarChar).Value = age;
cmd.Parameters.Add("#company_name", SqlDbType.VarChar).Value = company_name;
cmd.Parameters.Add("#company_address", SqlDbType.VarChar).Value = company_address;
cmd.Parameters.Add("#discription", SqlDbType.VarChar).Value = discription;
cmd.Parameters.Add("#dateofvisit", SqlDbType.VarChar).Value = dateofvisit;
cmd.Parameters.Add("#visitorsID", SqlDbType.VarChar).Value = visitorsID;
cmd.Parameters.Add("#status", SqlDbType.VarChar).Value = status;
cmd.Parameters.Add("#types", SqlDbType.VarChar).Value = types;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
BindData(this.TextBox1.Text);
}
}
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
}
}
}

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

DataGridView doesn't show any data from SQL Server datasource

I've been practicing with ADO.NET and SQL Server in a Windows Forms application, but I can't get table data into a DataGridView on the press of a button.
There are no errors and I make server connection checking. I have corresponding database and table name with some data in it.
Any ideas what I am doing wrong?
Here is code from the button:
private void button1_Click(object sender, EventArgs e)
{
string ConnectionString = "Server=DESKTOP-FV268LU;Database=ado_database;Integrated Security=true";
SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = ConnectionString;
myConnection.Open();
if (myConnection.State == ConnectionState.Open)
label1.Text = "YES!";
else if (myConnection.State != ConnectionState.Open)
label1.Text = "Nope!!";
string sql = "SELECT * FROM Main";
SqlDataAdapter myAdapter = new SqlDataAdapter(sql, myConnection);
DataSet myDataSet = new DataSet("Main");
myAdapter.Fill(myDataSet, "Main");
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = myDataSet.DefaultViewManager;
dataGridView1.Refresh();
}
You need to call after setting the DataSource
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = myDataSet.DefaultViewManager;
dataGridView1.DataBind();
EDIT
dataGridView1.DataSource = myDataSet.Tables[0];
dataGridView1.AutoGenerateColumns = true;
How about this?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using Excel = Microsoft.Office.Interop.Excel;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Configuration;
using System.Data.SqlClient;
namespace WindowsFormsApplication6
{
public partial class Form1 : Form
{
private DataTable table;
private DAL dal;
protected void Form_Load(object sender, EventArgs e)
{
dal = new DAL();
table = dal.GetData();
dataGridView1.DataSource = table;
}
public Form1()
{
InitializeComponent();
}
private void button5_Click(object sender, EventArgs e)
{
dal.UpdateData(table);
}
class DAL //data access layer
{
string connString = #"Server=EXCEL-PC\EXCELDEVELOPER;Database=AdventureWorksLT2012;Trusted_Connection=True;";
SqlDataAdapter da;
SqlCommandBuilder builder;
DataTable table;
SqlConnection conn;
public DataTable GetData()
{
table = new DataTable("dataGridView1");
conn = new SqlConnection(connString);
da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand(#"SELECT * FROM [SalesLT].[Product]", conn);
builder = new SqlCommandBuilder(da);
da.Fill(table);
return table;
}
public void UpdateData(DataTable table)
{
if (da != null && builder != null)
{
da.Update(table);
}
}
}
}
}
Here is another option for you to consider.
private void button6_Click(object sender, EventArgs e)
{
SqlConnection con = new System.Data.SqlClient.SqlConnection();
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Server=EXCEL-PC\\EXCELDEVELOPER;Database=AdventureWorksLT2012;Trusted_Connection=True;";
con.Open();
SqlDataAdapter da = new SqlDataAdapter();
for (int i = 0; i <= dataGridView1.Rows.Count - 2; i++)
{
String insertData = "INSERT INTO Import_List(Fname, Lname, Age) VALUES (#Fname, #Lname, #Age)";
SqlCommand cmd = new SqlCommand(insertData, con);
cmd.Parameters.AddWithValue("#Fname", dataGridView1.Rows[i].Cells[0].Value);
cmd.Parameters.AddWithValue("#Lname", dataGridView1.Rows[i].Cells[1].Value);
cmd.Parameters.AddWithValue("#Age", dataGridView1.Rows[i].Cells[2].Value);
da.InsertCommand = cmd;
cmd.ExecuteNonQuery();
}
con.Close();
}

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!");
}
}
}

Gridview not updating on pageload

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();
}
}
}

Categories