how to add database content to an asp.net page - c#

Hey I'm trying to add database info into my webpage. This is the code I am trying.
using System;
using System.Windows;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.Configuration;
using System.Data.SqlClient;
namespace DatabaseAddDemo
{
public partial class Content : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["key"] != null)
{
try
{
SqlConnection sqlConn = new SqlConnection(#"Data Source=officedev1;Initial Catalog=TestDatabase;User ID=sa;Password=Password11;pooling='true';Connect Timeout=3000; Max Pool Size=200;MultipleActiveResultSets='true'");
SqlCommand cmdPreWork = new SqlCommand(#"select * from CKEditor_Table where #ID = #key", sqlConn);
string key = Request.QueryString["keys"].ToString();
contentLiteral.Text = key;
cmdPreWork.Parameters.Add("#Information", SqlDbType.Char).Value = key;
Console.WriteLine(contentLiteral);
SqlDataAdapter daPreWork = new SqlDataAdapter(cmdPreWork);
DataTable dtPreWork = new DataTable();
daPreWork.Fill(dtPreWork);
Grid.DataSource = dtPreWork;
Grid.DataBind();
}
catch (Exception ex)
{
lblError.Text = "Could not open connection";
}
}
}
}
}
Whenever I try to display the information, I get the lblError text, telling me I could not open the connection. I'm not sure what to do. Please help.

You should be able to DEBUG this as stated in the comments. But in your code your select query expects a [Key] parameter and you are passing a [Information] parameter.
Change it as below:
SqlCommand cmdPreWork = new SqlCommand(#"select * from CKEditor_Table
where #ID = #key", sqlConn);
cmdPreWork.Parameters.Add("#key", SqlDbType.Char).Value = key;

Related

Invalid Connection String on .Net Teradata connection

I am trying to connect Teradata using .Net with the below code.
But when I execute it, it throws an error stating Invalid connection string
on
TdDataAdapter adapter = new TdDataAdapter(cn.ConnectionString,cmd.CommandText);
Here's the complete code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Teradata.Client.Provider;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
TdConnectionStringBuilder connectionStringBuilder = new TdConnectionStringBuilder();
connectionStringBuilder.DataSource = "URK";
connectionStringBuilder.Database = "DB";
connectionStringBuilder.UserId = "USERNAME";
connectionStringBuilder.Password = "PASSWORD";
connectionStringBuilder.AuthenticationMechanism = "LDAP";
TdConnection cn = new TdConnection();
cn.ConnectionString = connectionStringBuilder.ConnectionString;
cn.Open();
TdCommand cmd = new TdCommand("EXEC MACRONAME", cn);
TdDataReader reader = cmd.ExecuteReader();
TdDataAdapter adapter = new TdDataAdapter(cn.ConnectionString,cmd.CommandText);
DataSet ds = new DataSet();
adapter.Fill(ds);
myLabel.Text= ds.Tables[0].Rows[0]["event_id"].ToString();
cmd.Dispose();
cn.Close();
}
}
I tried using connectionStringBuilder.ConnectionString instead of the one used above but I still got the same error.
Just swap parameters
TdDataAdapter adapter = new TdDataAdapter(cmd.CommandText, cn.ConnectionString);
according to signature of TdDataAdapter constructor
public TdDataAdapter(
string commandText,
string connectionString
)
See docs

Why do i keep getting a blank form C#

I have a login_form and an admin_form. whenever I try to login I keep getting an empty form. why do I keep getting it?
this my login_form code:
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.IO;
namespace InternationalStudentsSociteySmartSystem
{
public partial class login_form : Form
{
public login_form()
{
InitializeComponent();
}
private void login_button_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.;Initial Catalog=ISSSS_DB;Integrated Security=True");
SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) from Table_1 where FullName='" + username_text.Text + "' and Password='" + password_text.Text + "' and Role='" + comboBox1.Text + "'", con);
DataTable dt = new System.Data.DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
SqlDataAdapter sda1 = new SqlDataAdapter("Select Role from Table_1 where FullName='" + username_text.Text + "' and Password='" + password_text.Text + "'", con);
DataTable dt1 = new System.Data.DataTable();
sda1.Fill(dt1);
if (dt1.Rows[0][0].ToString() == "Administrator")
{
admin_form ss = new admin_form();
ss.Show();
}
if (dt1.Rows[0][0].ToString() == "Committee")
{
committee_form ss = new committee_form();
ss.Show();
}
if (dt1.Rows[0][0].ToString() == "Secretary")
{
secretary_form ss = new secretary_form();
ss.Show();
}
}
}
}
}
and this is my admin_form code:
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.IO;
namespace InternationalStudentsSociteySmartSystem
{
public partial class admin_form : Form
{
SqlConnection conn = new SqlConnection("Data Source=TAREK-PC;Initial Catalog=ISSSS_DB;Integrated Security=True");
SqlCommand command;
string imgLoc;
SqlDataReader myReader;
public admin_form(string username)
{
InitializeComponent();
}
public admin_form()
{
// TODO: Complete member initialization
}
private void button1_Click(object sender, EventArgs e)
{
welcome_text.Text = "Welcome!";
try
{
string sql = "SELECT Image FROM Table_1 WHERE FullName='" + admin_name_text.Text + "'";
if (conn.State != ConnectionState.Open)
conn.Open();
command = new SqlCommand(sql, conn);
SqlDataReader reader = command.ExecuteReader();
reader.Read();
if (reader.HasRows)
{
byte[] img = (byte[])(reader[0]);
if (img == null)
admin_picturebox.Image = null;
else
{
MemoryStream ms = new MemoryStream(img);
admin_picturebox.Image = Image.FromStream(ms);
}
}
else
{
}
conn.Close();
}
catch (Exception ex)
{
conn.Close();
MessageBox.Show(ex.Message);
}
}
private void admin_form_Load(object sender, EventArgs e)
{
admin_picturebox.SizeMode = PictureBoxSizeMode.StretchImage;
}
private void register_committee_button_Click(object sender, EventArgs e)
{
register_committee_form rcf = new register_committee_form();
rcf.Show();
}
}
}
as you can see I also have to other forms which are committee_form and secretary_form (which they work just fine) but I didn't write their code yet. so I figured the problem is with admin form...
I appreciate the help, thanks.
You are calling the admin_form constructor that doesn't take any parameters. In that constructor the call to InitializeComponent is missing. So your admin_form is totally blank
You should add the call to InitializeComponent also to the parameterless constructor of admin_form.
public admin_form(string username)
{
InitializeComponent();
}
public admin_form()
{
// TODO: Complete member initialization
InitializeComponent();
}
As a side note, not related to your actual problem. Your code that access the database is vulnerable to Sql Injection hacks. And you will have a lot of problems to parse your input data. You should start immediately to use a parameterized query approach instead of string concatenation

I need to find the largest ID (prim key) in table, get the value & use it insert a new row in my table-need to use datasource1.SelectCommand

C# MSSql: I need to find the largest ID (primary key) in my table, get the value and use it to insert a new row in my table. I need to use datasource1.SelectCommand. I have tried sqlCommand, but that didn't work.
Below is the code as I have it so far:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Windows.Input;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Project
{
public partial class ListProperty : System.Web.UI.Page
{
//Other code here (Page_LOad, Dropdown list, etc)
protected void OnButtnClick(object sender, EventArgs e)
{
string sqlProc1 = "SELECT row from PROPERTY ORDER BY Id DESC Limit 1";
//SqlDataAdapter MxID = new SqlDataAdapter(sqlProc1,SqlDataSource1.SqlCacheDependency);
//SqlDataSource1.SelectCommand = sqlProc1;
//SqlConnection sqlConnection1 = new SqlConnection();
EntityDataSource cmd = new EntityDataSource();
//SqlCommand cmd = new SqlCommand();
Object returnValue;
cmd.CommandText = sqlProc1;
//cmd.CommandType = System.Data.CommandType.Text;
//cmd.Connection = sqlConnection1;
//sqlConnection1.Open();
returnValue = cmd.CommandText;
//sqlConnection1.Close();
Object MxID = returnValue;
MxID.ToString();
int MxIDint = (Int32)MxID + 1;
String strMxID = MxIDint.ToString();
sqlProc1 = "INSERT INTO PROPERTY(ID,Property_ID,Type_ID,Coordinates) VALUES(" + strMxID + ",'1','1','0.')";
SqlDataSource1.SelectCommand = sqlProc1;
//GridView1.DataBind(); //generates error
}
}
}
Please help!
use this SQL query:
select MAX(id) from PROPERTY;
queryResult = dbContext.Database
.SqlQuery<int>("SELECT Max(Id) from PROPERTY ")
.Single();
Check this out for more details:get a scalar value
I solved this by using Joe's suggestion to make the Id key self increment. I had to figure out how do that on my own though. I tried it before but I tried again and it did.

How to link separated class for database operations in website in ASP.net with the pages.aspx

Login Page: when the user logs in I should check if password and user
name is true or not through checking the table records in database.
Because I'm working using oop concept I created a separate class for
DB operations but I face a big problem that the text boxes in the
Login.aspx can't be seen in database class. The with
Registration.aspx I want to insert data of the new user but I can't
see the textboxes to take the strings inside them to add in the
database any help or any way to link those classes together.
here's my data Base class code
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.IO; using
System.Data.SqlClient; using System.Configuration; using
System.Data.Sql; using System.Data; using System.Web.UI.WebControls;
namespace Registration { };
/// /// Summary description for DataBase /// ///
//namespace Login.aspx { }; public class DataBase {
SqlDataReader rdr = null; public SqlCommand cmd_insert; public String USer=""; public String Pass="";
SqlConnection conn = null;
Login log = new Login();
public void Read_record()
{
try
{
//string ID = Request.QueryString["id"];
conn = new SqlConnection("Data Source=SHIMOFCIS-PC\\MYSQL;Initial Catalog=WebSite;Integrated
Security=SSPI");
SqlCommand cmd;
conn.Open();
cmd = new SqlCommand("select UserName,Password from Users ", conn);
rdr = cmd.ExecuteReader();
//using (var reader = cmd.ExecuteReader())
//{
if (rdr.Read()) // you don't need while loop
{
USer = rdr["UserName"].ToString();
Pass = rdr["Password"].ToString();
if (USer == log.UserName && Pass == log.Password)
{
rdr.Close();
conn.Close();
}
}
//}
}
finally
{
// close the reader
if (rdr != null)
{
rdr.Close();
}
// 5. Close the connection
if (conn != null)
{
conn.Close();
}
}
}
public void Insert_rows()
{
conn = new SqlConnection("Data Source=SHIMOFCIS-PC\\MYSQL;Initial Catalog=WebSite;Integrated
Security=SSPI");
conn.Open();
cmd_insert = new SqlCommand("INSERT INTO Users (UserName,Password,FullName,Address,Mobile,Email) VALUES (#value1 ,
#value2 , #value3 , #value4 , #value5 , #value6 , #value7)", conn);
} }
and this alogin.aspx code
` using System; using System.Collections.Generic; using
System.Linq; using System.Web; using System.Web.UI; using
System.Web.UI.WebControls;
public partial class Login : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
DataBase db = new DataBase();
db.Read_record();
if (db.USer == Login1.UserName && db.Pass == Login1.Password)
{
Response.Redirect("~/Home.aspx?UserName=" + Login1.UserName);
}
} }`
and in regestration.aspx i couldn't use create user control beacuse i
have to do specific fields to fill in so i couldn't depend on it to
solve the problem of not seein each like i do in login and it although
not working quiet well
I would highly suggest using an MVP pattern to separate the code, rather than a database class. The database class won't be able to do it directly. You can use a framework like Nucleo MVP or WebFormsMvp. For more on the MVP pattern, check out Dino Esposito's article.

C# Crystal Report Warnings The report you requested requires further information

I use C#.NET (WebApp) VS 2008 SP1
I want click next page from crystal report v.10.5.3700 (Framework 3.5) but it's show input data to next page
The report you requested requires further information
Server name:
Database name:
User name:
Password:
using System;
using System.Collections;
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.OleDb;
using System.Diagnostics;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Transactions;
using System.Drawing;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using CrystalDecisions.Web;
using CrystalDecisions.CrystalReports;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using CrystalDecisions.ReportSource;
namespace testReport
{
public partial class _cldClass : System.Web.UI.Page
{
SqlConnection objConn = new SqlConnection();
SqlCommand objCmd = new SqlCommand();
SqlDataAdapter dtAdapter = new SqlDataAdapter();
SqlConnection Conn;
DataSet ds = new DataSet();
DataTable dt = null;
string strConnString = WebConfigurationManager.ConnectionStrings["connDB"].ConnectionString;
string strSQL = null;
public string userDB
{
get { return WebConfigurationManager.AppSettings["userDB"]; }
}
public string pwdDB
{
get { return WebConfigurationManager.AppSettings["pwdDB"]; }
}
public string srvDB
{
get { return WebConfigurationManager.AppSettings["srvDB"]; }
}
public string dbName
{
get { return WebConfigurationManager.AppSettings["dbName"]; }
}
//protected void Page_Load(object sender, EventArgs e)
//{
//}
protected void Page_Init(object sender, EventArgs e)
{
TextBox2.Text = DateTime.Now.ToString("yyyy-MM-dd", new CultureInfo("en-US"));
Conn = new SqlConnection(strConnString);
Conn.Open();
if (Conn.State == ConnectionState.Open)
{
this.Label1.Text = "Connected";
}
else
{
this.Label1.Text = "Connect Failed";
}
}
protected void Button2_Click(object sender, EventArgs e)
{
strSQL = "SELECT * FROM fTime WHERE fDate='" + TextBox2.Text + "'";
objConn.ConnectionString = strConnString;
var _with1 = objCmd;
_with1.Connection = objConn;
_with1.CommandText = strSQL;
_with1.CommandType = CommandType.Text;
dtAdapter.SelectCommand = objCmd;
dtAdapter.Fill(ds, "cReport");
dt = ds.Tables[0];
dtAdapter = null;
objConn.Close();
objConn = null;
ReportDocument rpt = new ReportDocument();
rpt.Load(Server.MapPath("Report\\CrystalReport.rpt"));
rpt.SetDataSource(dt);
rpt.SetDatabaseLogon(userDB, pwdDB, srvDB, dbName);
CrystalReportViewer1.ReportSource = rpt;
CrystalReportViewer1.RefreshReport();
}
}
}
Thanks for your time :)
Normally you need to enter these informations when you created the report document directly from a database, that means when you used the report wizard and selected a table from the database. The report document itself contains the connection information to that data source but don't saves the logon information.
To overcome this you may create a typed dataset first from your database table you like to use in the report. Then create a report document and use the wizard to set the dataset (not the database table directly) as data source for your report. In your code you may then fill the dataset and just pass it to the report.
I ran into this today, and the reason I got the error was because I didn't have the correct provider installed on my server.
What I did was this:
CrystalReportViewer1.EnableDatabaseLogonPrompt = false;
That gave me a new error: Logon failed. Details: ADO Error Code: 0x Source: ADODB.Connection Description: Provider cannot be found. It may not be properly installed
After that, I checked the OLE DB provider in the report. Installing the SQL Native Client tools fixed the problem.

Categories