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
Related
I had opened a related topic before, but I realized the problem now. When I set allow paging correctly in the properties of gridview in web form.aspx, I get this error. I don't know if the codes I wrote in aspx.cs browser cause this problem, please help
'''
public partial class WebForm1 : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=MERIH-PC;Initial Catalog=aspidus;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GVbind();
}
}
void clear()
{
txtName.Text = "";
txtPhone.Text = "";
txtAdd.Text = "";
}
protected void btnInsert_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand(#"INSERT INTO [dbo].[idus] VALUES ('" + txtName.Text + "', '" + txtPhone.Text + "', '" + txtAdd.Text + "')", con);
int t = cmd.ExecuteNonQuery();
if (t > 0)
{
Response.Write("<script>alert('Data inserted successfully') </script>");
con.Close();
}
GVbind();
clear();
}
//protected void btnDelete_Click(object sender, EventArgs e)
//{
// SqlCommand cmd = new SqlCommand(#"DELETE FROM [dbo].[idus]
// WHERE [ID]='" + txtID.Text + "'", con);
// con.Open();
// cmd.ExecuteNonQuery();
// Response.Write("Data deleted successfully");
// con.Close();
//}
//protected void btnUpdate_Click(object sender, EventArgs e)
//{
// SqlCommand cmd = new SqlCommand(#"UPDATE [dbo].[idus]
// SET[ID] = '" + txtID.Text + "',[name] = '" + txtName.Text + "',[phone] = '" + txtPhone.Text + "',[address] = '" + txtAdd.Text + "' WHERE [ID]= '" + txtID.Text + "'", con);
// con.Open();
// cmd.ExecuteNonQuery();
// Response.Write("Data updated successfully");
// con.Close();
//}
protected void GVbind()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from [dbo].[idus]", con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == true)
{
GridView1.DataSource = dr;
GridView1.DataBind();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GVbind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int ID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
string name = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
string phone = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
string address = ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
con.Open();
SqlCommand cmd = new SqlCommand("update [dbo].[idus] set name='" + name + "', phone='" + phone + "', address='" + address + "' where ID = '" + ID + "'", con);
int t = cmd.ExecuteNonQuery();
if (t > 0)
{
con.Close();
Response.Write("<script>alert('Data has been updated') </script>");
GridView1.EditIndex = -1;
GVbind();
}
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
GVbind();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
con.Open();
int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
SqlCommand cmd = new SqlCommand("delete from [dbo].[idus] where ID='" + id + "'", con);
int t = cmd.ExecuteNonQuery();
if (t > 0)
{
con.Close();
Response.Write("<script>alert('Data has been deleted') </script>");
GridView1.EditIndex = -1;
GVbind();
}
}
protected void DisplayData()
{
SqlConnection con = new SqlConnection("Data Source=MERIH-PC;Initial Catalog=aspidus;Integrated Security=True");
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("select * from [dbo].[idus]", con);
con.Open();
da.Fill(dt);
con.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_PageIndexChanging1(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GVbind();
'''
enter image description here
enter image description here
You are assigning the GV a "reader", and you can't use a reader - you have to fill a table, or use some other ennumberable collection. Say like a data table.
So, this code:
protected void GVbind()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from [dbo].[idus]", con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == true)
{
GridView1.DataSource = dr;
GridView1.DataBind();
}
}
Change to :
protected void GVbind()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from [dbo].[idus]", con);
Datatable dt = new dt();
dt.load(cmd.ExecuteReader());
GridView1.DataSource = dt;
GridView1.DataBind();
}
So, while you can "shove" the GV to a reader directly? If you going to use paging, then you can't shove into the GV a reader - since paging does not work with a non innumerable type of data set (like a reader).
So, just load up a data table. And note how I did not even need a data adaptor to load up a data table (the data table has a .Load command for you. (so, you can shorten your other code this way also).
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
}
i am trying to edit data from a database directly on datagridview, but for some reason im having a error.
Object reference not set to an instance of an object
I tried some differents approach but didn't worked, had the same error.
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.Sql;
using System.Data.SqlClient;
using System.Threading;
using System.Runtime.InteropServices;
namespace WindowsFormsApplication2
{
public partial class Principal : Form
{
SqlConnection con;
SqlDataAdapter adap;
SqlCommandBuilder scb;
DataSet ds;
SqlCommandBuilder cmdb1;
public Principal()
{
InitializeComponent();
Load += new EventHandler(Principal_Load);
}
private void fusionButton1_Click(object sender, EventArgs e)
{
AdicionarFornecedor add = new AdicionarFornecedor();
add.ShowDialog();
}
private void fusionButton2_Click(object sender, EventArgs e)
{
VerFornecedores add = new VerFornecedores();
add.ShowDialog();
}
private void Principal_Load(object sender, EventArgs e)
{
try
{
SqlConnection con;
SqlDataAdapter adap;
DataSet ds;
con = new SqlConnection();
con.ConnectionString = (#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|PAPPloran.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
adap = new SqlDataAdapter("select * from Pagamentos", con);
ds = new System.Data.DataSet();
adap.Fill(ds, "P");
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show("Erro\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void fusionTheme1_Click(object sender, EventArgs e)
{
}
private void fusionButton3_Click(object sender, EventArgs e)
{
AdicionarPagamento add2 = new AdicionarPagamento();
add2.ShowDialog();
}
private void fusionButton4_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|PAPPloran.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
SqlCommand cmd = new SqlCommand(#"delete from Pagamentos WHERE (IdFornecedor = '" + textBox3.Text + "')", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Dados Eliminados com Sucesso ! ");
textBox3.Text = "";
con.Close();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
con = new SqlConnection();
con.ConnectionString = (#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|PAPPloran.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from Pagamentos where NomeFornecedor like ('" + textBox1.Text + "%')";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void fusionButton5_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
if (row.Cells[7].Value != null && row.Cells[7].Value.ToString() == "1- Pago")
{
row.DefaultCellStyle.BackColor = Color.GreenYellow;
}
else
{
row.DefaultCellStyle.BackColor = Color.Tomato;
}
}
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;
[DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();
private void fusionTheme1_MouseDown(object sender, MouseEventArgs e)
{
ReleaseCapture();
SendMessage(this.Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
private void fusionButton6_Click(object sender, EventArgs e)
{
this.Close();
}
private void button1_Click(object sender, DataGridViewCellFormattingEventArgs e)
{
}
private void fusionButton7_Click(object sender, EventArgs e)
{
SqlConnection con;
SqlDataAdapter adap;
DataSet ds;
con = new SqlConnection();
con.ConnectionString = (#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|PAPPloran.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
adap = new SqlDataAdapter("select * from Pagamentos", con);
ds = new System.Data.DataSet();
adap.Fill(ds, "P");
dataGridView1.DataSource = ds.Tables[0];
}
private void fusionButton8_Click(object sender, EventArgs e)
{
con.ConnectionString = (#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|PAPPloran.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
SqlCommand cmd = new SqlCommand(#"delete from Pagamentos WHERE (NomeFornecedor = '" + textBox3.Text + "')", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Dados Eliminados com Sucesso ! ");
textBox3.Text = "";
con.Close();
}
private void Principal_Load_1(object sender, EventArgs e)
{
}
private void fusionButton9_Click(object sender, EventArgs e)
{
try
{
cmdb1 = new SqlCommandBuilder(adap);
adap.Update(ds);
MessageBox.Show("Data updated", "Update", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
http://i.stack.imgur.com/1lSIl.png
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();
}
}
}
public partial class Admin_Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
SqlConnection con = null;
ConectionStrings cs = new ConectionStrings();
SqlCommand comm = null;
SqlDataReader reader = null;
SqlDataAdapter da;
protected void btnadmin_login_Click(object sender, EventArgs e)
{
con = new SqlConnection(cs.Db);
con.Open();
//string logincheck = "select * from Admin_login where admin_name =#username and admin_pwd=#password";
string login = " Select * from Admin_login where admin_name = '" + txtadmin_name.Text + "' and admin_pwd = '" + txtadmin_pwd.Text + "' ";
comm=new SqlCommand(login,con);
// comm.Parameters.AddWithValue("#username", txtadmin_name.Text);
// // da = new SqlDataAdapter(login, con);
// comm.Parameters.AddWithValue("#admin_pwd", txtadmin_pwd.Text.Trim());
//
reader = comm.ExecuteReader();
if (reader.Read())
{
Response.Redirect("Admin Add_Books.aspx");
}
else
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Invalid Username and Password')</script>");
}
con.Close();
}
}
and
public partial class Admin_Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
SqlConnection con = null;
ConectionStrings cs = new ConectionStrings();
SqlCommand comm = null;
SqlDataReader reader = null;
SqlDataAdapter da;
protected void btnadmin_login_Click(object sender, EventArgs e)
{
con = new SqlConnection(cs.Db);
con.Open();
//string logincheck = "select * from Admin_login where admin_name =#username and admin_pwd=#password";
string login = " Select * from Admin_login where admin_name = '" + txtadmin_name.Text + "' and admin_pwd = '" + txtadmin_pwd.Text + "' ";
comm=new SqlCommand(login,con);
// comm.Parameters.AddWithValue("#username", txtadmin_name.Text);
// // da = new SqlDataAdapter(login, con);
// comm.Parameters.AddWithValue("#admin_pwd", txtadmin_pwd.Text.Trim());
//
reader = comm.ExecuteReader();
if (reader.Read())
{
Response.Redirect("Admin Add_Books.aspx");
}
else
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Invalid Username and Password')</script>");
}
con.Close();
}
}
Everything is alright but when log-out and url same copy my home page same and back to the before page
Hey you need to first understand the concept properly.
One is that you have used SQLDataAdapter and also opened and closed the connection. No you dont need to because SQLDataAdapter is use for closed Connection. Search for Open and Close connection in Asp.net On Google and read on microsoft official Site.
Second, Comming to your point, I just cannot see that you have used session anywhere. Upon successful login you should save some data in Session and on each page load check that session is not empty. So if it is then redirect again to login page and this way unautorized users cannot see your page. Check below example.
if (reader.Read())
{
Session["AdminLoginDetails"] = "logged In"; //Should actually be login details(datatable)
Response.Redirect("Admin Add_Books.aspx");
}
Now on each page's load event (that should not be visible without login)
protected void Page_Load(object sender, EventArgs e)
{
if (Session["AdminLoginDetails"] == null)
{
Response.Redirect("../Default.aspx");
}
}
Hope it helps.
And Also you should edit your question and not to add answer as a question. Use Edit button Below your Question to edit and make your question understandable. Your question was simple but your way of questioning made it difficult.
This is my admin login panel
public partial class Admin_Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
SqlConnection con = null;
ConectionStrings cs = new ConectionStrings();
SqlCommand comm = null;
SqlDataReader reader = null;
SqlDataAdapter da;
protected void btnadmin_login_Click(object sender, EventArgs e)
{
con = new SqlConnection(cs.Db);
con.Open();
//string logincheck = "select * from Admin_login where admin_name =#username and admin_pwd=#password";
string login = " Select * from Admin_login where admin_name = '" + txtadmin_name.Text + "' and admin_pwd = '" + txtadmin_pwd.Text + "' ";
comm=new SqlCommand(login,con);
// comm.Parameters.AddWithValue("#username", txtadmin_name.Text);
// // da = new SqlDataAdapter(login, con);
// comm.Parameters.AddWithValue("#admin_pwd", txtadmin_pwd.Text.Trim());
//
reader = comm.ExecuteReader();
if (reader.Read())
{
Response.Redirect("Admin Add_Books.aspx");
}
else
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Invalid Username and Password')</script>");
}
con.Close();
}
}
when i click login button when open my other page and when i log-out my page
then its back again login panel ..... everything is alright But One Probelm when i click backpage its return my internal page without log in Or when i coppy url my internal page and after log-out again i put my url in browser when this page show without login
But i have no password save browser
this page code here
public partial class Admin_Add_Books : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ConectionStrings cs = new ConectionStrings();
SqlConnection con = new SqlConnection(cs.Db);
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Library order by mem_id", con);
DataTable tb = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(tb);
tb.AcceptChanges();
GridView_all_records.DataSource = tb;
GridView_all_records.DataBind();
con.Close();
}
protected void Button1_Click1(object sender, EventArgs e)
{
Response.Redirect("Admin Login.aspx");
}
}