insert data into database in asp.net - asp.net

I want to insert data into database by using following code, but it causes an error that
No mapping exists from object type System.Web.UI.WebControls.TextBox to a known managed provider native type.
I don't understand what can I do
Here is the code
protected void Button1_Click(object sender, EventArgs e)
{
string con = "Data Source=Mir-pc;Initial Catalog=mir1;Integrated Security=True";
SqlConnection myconn = new SqlConnection(con);
string query = "insert into [Resevation] name,cellnumber,guest,tabl,date values(#name,#cellnumber,#guest,#tabl,#date)";
SqlCommand mycmd = new SqlCommand(query, myconn);
mycmd.Parameters.AddWithValue("#name", nameTextBox2);
mycmd.Parameters.AddWithValue("#cellnumber" ,cellTextBox3);
mycmd.Parameters.AddWithValue("#guest" , guestTextBox);
mycmd.Parameters.AddWithValue("#tabl", tableTextBox);
mycmd.Parameters.AddWithValue("#date", DateTextbox);
myconn.Open();
mycmd.ExecuteNonQuery();
myconn.Close();
}

Try like this :
protected void Button1_Click(object sender, EventArgs e)
{
string con = "Data Source=Mir-pc;Initial Catalog=mir1;Integrated Security=True";
SqlConnection myconn = new SqlConnection(con);
string query = "insert into [Resevation] name, cellnumber, guest, tabl, date values(#name, #cellnumber, #guest, #tabl, #date)";
SqlCommand mycmd = new SqlCommand(query,myconn);
mycmd.Parameters.AddWithValue("#name", nameTextBox2.Text);
mycmd.Parameters.AddWithValue("#cellnumber" ,cellTextBox3.Text);
mycmd.Parameters.AddWithValue("#guest" , guestTextBox.Text);
mycmd.Parameters.AddWithValue("#tabl", tableTextBox.Text);
mycmd.Parameters.AddWithValue("#date", DateTextbox);
myconn.Open();
mycmd.ExecuteNonQuery();
myconn.Close();
}

Related

ASP.Net Server prints data from DB but won't write to DB

I have an issue with the connectionstring or something similiar I assume. since data is printed from DB but won't write to DB using the INSERT Query string.
here's the .cs code part:
protected void Page_Load(object sender, EventArgs e)
{
Load_Data();
}
protected void Load_Data()
{
DataTable dtUsers = new DataTable();
// connect to sql
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString);
// create sql
string sql = "SELECT Username, Fullname, Email FROM Users;";
// command
SqlCommand cmd = new SqlCommand(sql, con);
// load data to dt
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
dtUsers.Load(reader);
con.Close();
// print data to gridview
GridView1.DataSource = dtUsers;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
// connect to sql
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString);
// create query
string sql = "INSERT INTO Users (UserName,Passowrd,Email,FullName) VALUES ('" + txtUsername.Text + "','"+ txtPwd.Text + "','"+ txtEmail.Text + "','" + txtFullName.Text + "');";
// command
SqlCommand cmd = new SqlCommand(sql, con);
// save data to db
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
thank you!

ASP.NET Connection with Oracle DB

I do not understand why I have this error message. No code is used for the connection, only an SQLDatasource and a grid view. I am using this code:
protected void Page_Load(object sender, EventArgs e)
{
try
{
using(OracleConnection conn = new OracleConnection("....."))
using(OracleCommand cmd = new OracleCommand("select * from t1", conn))
{
conn.Open();
using(OracleDataReader reader = cmd.ExecuteReader())
{
DataTable dataTable = new DataTable();
dataTable.Load(reader);
ListBox1.DataSource = dataTable;
}
}
}
catch (Exception ex)
{
Label1.Text=ex.Message;
}
}
First you have install oracle data access client and then try this
following code
protected void Button1_Click(object sender, EventArgs e)
{
string connectionString = "Data Source = DESCRIPTION = " +
"(ADDRESS = (PROTOCOL = TCP)(HOST = ho
List item
st_name)(PORT = 1521))" +
"(CONNECT_DATA =" +
" (SERVER = DEDICATED)" +
" (SERVICE_NAME = your_service_name)" +
")" + ");User Id = ID;Password=Password;";
Oracle.DataAccess.Client.OracleConnection con = new Oracle.DataAccess.Client.OracleConnection();
con.ConnectionString = connectionString;
con.Open();
Oracle.DataAccess.Client.OracleCommand cmd = new Oracle.DataAccess.Client.OracleCommand();
cmd.CommandText = "select ref_no from money_trn where ref_no=20170733";
cmd.Connection = con;
con.Close();
cmd.CommandType = System.Data.CommandType.Text;
Oracle.DataAccess.Client.OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
TextBox1.Text = dr.GetString(0);
}
You can't use SqlConnection for the Oracle!
First of all, you have to add connectionString into web.config to connection with Oracle.
Secondly, Add reference System.Data.OracleClient to your project.
Then, replace SqlConnection with OracleConnection. Everything, what you used with Sql, you have to replace with Oracle.

Error in running simple Web application "System.ComponentModel.Win32Exception: The network path was not found"

I tried to run this code but it raise an error at con.Open() method
"System.ComponentModel.Win32Exception: The network path was not found"
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string cs = "server = (localdb)\v11.0 ; database = DepartmentsAndEmployees ; integrated security=true";
SqlConnection conn = new SqlConnection(cs);
SqlCommand com = new SqlCommand("select * from Employees", conn);
conn.Open();
GridView1.DataSource = com.ExecuteReader();
GridView1.DataBind();
conn.Close();
}
}
This is because it can not find the server. There is something wrong with your connection string.
Try this connection string builder:
http://www.developerfusion.com/tools/sql-connection-string/
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring(v=vs.110).aspx

dropdownlist Insert always the default value

I have one dropdownlist with data from database table and i want do insert with this ddl + 2 texbox field in another table . The insert work but always insert the default dropdownList witch displays first. wHat am i missing?
protected void Page_Load(object sender, EventArgs e)
{
string connectionString = cs.getConnection();
string query = "SELECT Id, NAME FROM PROFITCATEGORIES";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand command = new SqlCommand(query, myConnection);
using (SqlDataReader rdr = command.ExecuteReader())
{
DropDownListCategory.DataSource = rdr;
DropDownListCategory.DataTextField = "Name";
DropDownListCategory.DataValueField = "ID";
DropDownListCategory.DataBind();
}
}
}
protected void ButtonSave_Click(object sender, EventArgs e)
{
if (String.IsNullOrWhiteSpace(TextBoxValue.Text))
return;
string connectionString = cs.getConnection();
string insertSql = "INSERT INTO profits(Value,DateCreate,IdCategory,IdUser) VALUES(#Value, #DateCreate,#CategoryId,#UserId)";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand command = new SqlCommand(insertSql, myConnection);
//параметризация се прави тук за да се избегне SQL Injection
command.Parameters.AddWithValue("#Value", TextBoxValue.Text);
command.Parameters.AddWithValue("#DateCreate", TextBoxData.Text);
command.Parameters.AddWithValue("#CategoryId", DropDownListCategory.SelectedValue);
command.Parameters.AddWithValue("#UserId", cui.getCurrentId());
command.ExecuteNonQuery();
//пренасочваме заявката към същата страница за да се видят новите резултати и да се избегне проблем с дублиране на инсерт при рефреш на страницата
Response.Redirect("~/Profit.aspx");
myConnection.Close();
}
TextBoxValue.Text = string.Empty;
}
You're re-binding the list on every page load. Wrap the data-binding code in an if (!IsPostBack) block.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Bind the list here...
}
}
Everytime you press the asp:button the page gets reloaded, and the code in the page_load method gets initialised again. That's why the default item is always inserted in your database.
Put this around your code in the page_load: (if (!Page.IsPostback))
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.isPostback)
{
string connectionString = cs.getConnection();
string query = "SELECT Id, NAME FROM PROFITCATEGORIES";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand command = new SqlCommand(query, myConnection);
using (SqlDataReader rdr = command.ExecuteReader())
{
DropDownListCategory.DataSource = rdr;
DropDownListCategory.DataTextField = "Name";
DropDownListCategory.DataValueField = "ID";
DropDownListCategory.DataBind();
}
}
}
}
Use the AppendDataBoundItems property and set it to true, and only bind on PostBack:
How Do I Add an Additional Item To a Databound DropDownList Control in ASP.NET?
ListControl.AppendDataBoundItems Property

The ConnectionString property has not been initialized

My connection string is placed in web.config as follows.
<connectionStrings>
<add name="empcon" connectionString="Persist Security Info=False;User ID=sa;Password=abc;Initial Catalog=db5pmto8pm;Data Source=SOWMYA-3BBF60D0\SOWMYA" />
</connectionStrings>
and the code of program is...
public partial class empoperations : System.Web.UI.Page
{
string constr = null;
protected void Page_Load(object sender, EventArgs e)
{
ConfigurationManager.ConnectionStrings["empcon"].ToString();
if (!this.IsPostBack)
{
fillemps();
}
}
public void fillemps()
{
dlstemps.Items.Clear();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["empcon"].ConnectionString);
con.ConnectionString = constr;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from emp";
cmd.Connection = con;
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
ListItem lt = new ListItem();
lt.Text = reader["ename"].ToString();
lt.Value = reader["empno"].ToString();
dlstemps.Items.Add(lt);
}
reader.Close();
}
catch (Exception er)
{
lblerror.Text = er.Message;
}
finally
{
con.Close();
}
i am totally new to programing....
i am able to run this application with er.message in label control as "the connection string property has not been initialized"
i need to retrieve the list of names of employees from the emp table in database into the dropdownlist and show them to the user...
can any one please fix it...
Where are you initializing your constr variable? It looks like you can leave that line out.
Also: just use using
using(SqlConnection con = new SqlConnection(
ConfigurationManager.ConnectionStrings["empcon"].ConnectionString)
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
//Rest of your code here
}
}
Side note: Don't use Select * From. Call out your columns: Select empname, empno From...
You are not assigning ConfigurationManager.ConnectionStrings["empcon"].ToString(); to string constr
protected void Page_Load(object sender, EventArgs e)
{
constr = ConfigurationManager.ConnectionStrings["empcon"].ToString();
...
will probably solve your problem for the time being.

Resources