I have an asp.net application which is a random generator of places.
At present I am the values sat in my code behind but I would like to move these into my SQL Server DB but I have no idea on how to do this. For reference I am using SQL Server Management Studio.
Is this possible or am I just over complicating it?
Code Behind
protected void BtnDecideForMe_Click(object sender, EventArgs e)
{
List<string> Eat = new List<string>();
Eat.Add("Chinese Buffet");
Eat.Add("Harvester");
Eat.Add("Frankie & Benny's");
Eat.Add("Hungry Horse");
Eat.Add("Blaize");
Eat.Add("Chiquito");
Eat.Add("Cafe Football");
Eat.Add("Nando's");
Random Place = new Random();
int Places = Place.Next(0, Eat.Count);
txtDestination.Text = Eat[Places];
}
View
<div class="row">
<div class="col-sm-3">
<asp:TextBox class="form-control" ID="txtDestination" runat="server" disabled></asp:TextBox>
</div>
<div class="col-sm-2">
<asp:Button class="btn btn-success" ID="BtnDecideForMe" runat="server" Text="Decide For Me" OnClick="BtnDecideForMe_Click" />
</div>
</div>
Code For Suggestion But Cant Get It Working
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;
namespace PaydayLunchGenerator
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void BtnDecideForMe_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=DEV-116\\ONLINE;" +
"Initial Catalog=PaydayLunch;" +
"Integrated Security=True;";
conn.Open();
//using (SqlConnection conn = new SqlConnection(PaydayLunchConnectionString1))
using (SqlCommand cmd = new SqlCommand("dbo.GetRandomPlace", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
// set up the parameters
cmd.Parameters.Add("#OutputVar", SqlDbType.VarChar).Direction = ParameterDirection.Output;
// open connection and execute stored procedure
conn.Open();
cmd.ExecuteNonQuery();
// read output value from #OutputVar
string place = Convert.ToString(cmd.Parameters["#OutputVar"].Value);
conn.Close();
txtDestination.Text = place;
}
}
}
}
You can achieve this by creating a view in SQL server and loading that view into a dataset. That way you can select from the dataset and refresh the data whenever you require.
Populating Dataset
Note - You could even go a step further and create a stored procedure that will just give you a random value from the table on demand :)
Create a stored procedure with an output variable, then inside create a select like this
CREATE PROC sp_RandomPlace
#OutputVar nvarchar(100) OUTPUT
AS
SET #OutputVar = (select top 1 percent Place from [PlaceTable] order by newid())
Then in your c#
using(SqlConnection conn = new SqlConnection(ConnectionString ))
using(SqlCommand cmd = new SqlCommand("dbo.sp_RandomPlace", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
// set up the parameters
cmd.Parameters.Add("#OutputVar", SqlDbType.Nvarchar).Direction = ParameterDirection.Output;
// open connection and execute stored procedure
conn.Open();
cmd.ExecuteNonQuery();
// read output value from #OutputVar
string place= Convert.ToString(cmd.Parameters["#OutputVar"].Value);
conn.Close();
}
The code above is untested but you get the jist
With the thanks to Alec, i manged to get it working eventually using the following:
protected void BtnDecideForMe_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=DEV-116\\ONLINE;Initial Catalog=PaydayLunch;Integrated Security=True";
using (SqlCommand cmd = new SqlCommand("dbo.GetRandomPlace", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
// set up the parameters
cmd.Parameters.Add("#OutputVar", SqlDbType.VarChar, 25).Direction = ParameterDirection.Output;
// open connection and execute stored procedure
conn.Open();
cmd.ExecuteNonQuery();
// read output value from #OutputVar
string place = Convert.ToString(cmd.Parameters["#OutputVar"].Value);
conn.Close();
txtDestination.Text = place;
}
}
Related
Here's a little background on what I'm doing...
I'm writing a C# web app. On the main page, I have a data input form with about 25 individual Dropdownlists. I created a table called options, and it's pretty simple (ID, Category, Option). Each option I create is categorized so my query will only include options that match the category I'm looking up. Each Category matches one of the 25 Dropdownlists I need to populate.
So I'm able to get a few of these populated on the form and they work great. I'm concerned that the re-writing of this code (with slight variation of the DDlist name and category name) will cause the code to be much longer. Is there a way I can create a class of it's own and pass parameters to the class so it only returns me data from the correct category and populates the correct Dropdownlist? Here's some sample code I have so far for 2 DD fields. The DDStationList and DDReqeustType are the names of 2 of the 25 Dropdownlists I have created:
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;
using System.Configuration;
using System.Drawing;
namespace TEST
{
public partial class _Default : Page
{
//Main connection string
string SqlConn = ConfigurationManager.AppSettings["SqlConn"];
string qryRequestType = ConfigurationManager.AppSettings["qryRequestTypes"];
string qryStationNumbers = ConfigurationManager.AppSettings["qryStationNumbers"];
protected void Page_Load(object sender, EventArgs e)
{}
protected void BtnAddNew_Click(object sender, EventArgs e)
{
//GET Request Types
DataTable RequestTypes = new DataTable();
SqlConnection Conn = new SqlConnection(SqlConn);
{
SqlDataAdapter adapter = new SqlDataAdapter(qryRequestType, Conn);
adapter.Fill(RequestTypes);
DDRequestType.DataSource = RequestTypes;
DDRequestType.DataTextField = "Option";
DDRequestType.DataValueField = "Option";
DDRequestType.DataBind();
}
// Get Stations
DataTable Stations = new DataTable();
SqlConnection Conn = new SqlConnection(SqlConn);
{
SqlDataAdapter adapter = new SqlDataAdapter(qryStationNumbers, Conn);
adapter.Fill(Stations);
DDStationList.DataSource = Stations;
DDStationList.DataTextField = "Option";
DDStationList.DataValueField = "Option";
DDStationList.DataBind();
}
}
protected void BtnSubmit_Click(object sender, EventArgs e)
{
//More stuff to do here for submit code
}
}
}
Example queries from my config file that correspond to above code:
SELECT [Option] FROM Table WHERE Category = 'RequestType';
SELECT [Option] FROM Table WHERE Category = 'Station';
So, is it possible I can create a class that I can pass the Option's Category into that runs the query Like this:
SELECT [Option] FROM Table WHERE Category = #Category;
...and then populate the correct Dropdownlist (need to do this 25 times)?
If I'm not clear on my question, I'll be happy to explain further.
Why not create a stored procedure instead?
using (SqlConnection con = new SqlConnection(dc.Con)) {
using (SqlCommand cmd = new SqlCommand("sp_GetCategory", con)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Category", SqlDbType.VarChar).Value = txtCategory.Text;
con.Open();
var results = cmd.ExecuteReader();
}
}
OR include the parameter
string sql = "SELECT [Option] FROM Table WHERE Category = #Category";
using (SqlConnection con = new SqlConnection(dc.Con)) {
using (SqlCommand cmd= new SqlCommand(sql, con)) {
cmd.Parameters.Add("#Category", SqlDbType.VarChar).Value = txtCategory.Text;
con.Open();
var results = cmd.ExecuteReader();
}
}
EDIT
class Category
{
/* properties */
/* method */
public List<Category> GetCategory(string selectedCategory)
{ /* Method statements here */ }
}
I have two tables in my database. Let's say table A and table B. table A values are put in checkedlistbox. The selected values in checkedlistbox then are put into table B. I tried to make a code however it wont work. Do you have any idea on how to make this problem work?
thanks ahead guys.
by the way im using c#.
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 Npgsql;
namespace WindowsFormsApplication1
{
public partial class Form8 : Form
{
public Form8()
{
InitializeComponent();
this.Load += Form8_Load;
button2.Click += button2_Click;
}
private void Form8_Load(object sender, EventArgs e)
{
string connstring = ("Server=localhost;Port=5432;User Id=postgres;Password=021393;Database=postgres;");
NpgsqlConnection conn = new NpgsqlConnection(connstring);
NpgsqlCommand cmd = new NpgsqlCommand("SELECT conname FROM condition", conn);
cmd.CommandType = CommandType.Text;
conn.Open();
using (NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
da.Fill(dt);
((ListBox)checkedListBox1).DataSource = dt;
((ListBox)checkedListBox1).DisplayMember = "conname";
((ListBox)checkedListBox1).DisplayMember = "conid";
string[] condition = dt.Rows[0]["conname"].ToString().Split(',');
}
}
private void button2_Click(object sender, EventArgs e)
{
string connstring = ("Server=localhost;Port=5432;User Id=postgres;Password=021393;Database=postgres;");
NpgsqlConnection conn = new NpgsqlConnection(connstring);
NpgsqlCommand cmd = new NpgsqlCommand("Insert into famhistory(famid) Values (#famid)", conn);
conn.Open();
cmd.Parameters.AddWithValue("#famid", checkedListBox1.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Data has been saved");
conn.Close();
}
}
}
You have to iterate through all the selected items:
//check if any item is selected
if (checkedListBox1.SelectedItems.Count > 0)
{
//connect to database
string connstring = ("Server=localhost;Port=5432;User Id=postgres;Password=021393;Database=postgres;");
NpgsqlConnection conn = new NpgsqlConnection(connstring);
conn.Open();
//loop through all selected items
foreach (object item in checkedListBox1.CheckedItems)
{
//convert item to string
string checkedItem = item.ToString();
//insert item to database
NpgsqlCommand cmd = new NpgsqlCommand("Insert into famhistory(famid) Values (#famid)", conn);
cmd.Parameters.AddWithValue("#famid", checkedItem); //add item
cmd.ExecuteNonQuery();
}
//close connection
conn.Close();
MessageBox.Show("Data has been saved");
}
Note: I am executing all insert commands in one open connection, because opening and closing connection frequently is not best practice.
I have an ASPX page that has a drop down on it.
<div>
<p>Pick a customer to show their order(s)</p>
<asp:DropDownList ID="customerSelect" AutoPostBack="true" runat="server" OnSelectedIndexChanged="customerSelect_SelectedIndexChanged"></asp:DropDownList>
</div>
I want the options in the drop down to be populated from a database of customer names.
Here is what my database looks like
Here is my code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
populateDropDown();
customerSelect_SelectedIndexChanged(null, null);
}
}
public void populateDropDown()
{
SqlCommand cmd = new SqlCommand("SELECT * FROM [Orders]", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
cmd.Connection.Open();
SqlDataReader ddlValues;
ddlValues = cmd.ExecuteReader();
customerSelect.DataSource = ddlValues;
customerSelect.DataValueField = "OrderID";
customerSelect.DataTextField = "CustomerName";
cmd.Connection.Close();
cmd.Connection.Dispose();
}
I've used this code before. So I must be missing something simple but I'm not sure what it is.
EDIT
I am getting no errors. The code compiles. But the drop down list remains blank.
Well, I think you forget to bind your dropdownlist like;
customerSelect.DataBind();
And use using statement to dispose your SqlCommand, SqlConnection and SqlDataReader instead of calling .Dispose() method manually.
using(SqlConnection con = new SqlConnection(connString))
using(SqlCommand cmd = con.CreateCommand())
{
...
...
using(SqlDataReader ddlValues = cmd.ExecuteReader())
{
...
}
}
I am completely blind with this Error. I'm more of a Java man than an ASP one. So here is my code and my question :
Here is my code that produce the error :
protected void ButtonOk_Click(object sender, EventArgs e)
{
// OracleConnection connect = new OracleConnection();
// connect.ConnectionString = ConfigurationManager.ConnectionStrings["Absensi2.Properties.Settings.Setting"].ConnectionString;
//// SqlConnection connect = new SqlConnection(getConnection());
var sql = "insert into master_dosen('NIP','NAMA_DOSEN','KETERANGAN') values (:NIP, :NAMA_DOSEN, :KETERANGAN)";
using (OracleConnection c = new OracleConnection(ConfigurationManager.ConnectionStrings["Absensi2.Properties.Settings.Setting"].ConnectionString))
{
c.Open();
using (OracleCommand cmd = new OracleCommand(sql, c))
{
cmd.Parameters.Add(":NIP", TextBoxNIP.Text);
cmd.Parameters.Add(":NAMA_DOSEN", TextBoxNamaDosen.Text);
cmd.Parameters.Add(":KETERANGAN", TextBoxKeterangan.Text);
cmd.ExecuteNonQuery();
GridView1.DataBind();
}
c.Close();
}
The error is :
ORA-00928: missing SELECT keyword
in line cmd.ExecuteNonQuery();
I already search and it says deprecated. is it true?
NB : I am using ODP.NET, and I am using visual studio 2010.
The problem with your query is that you are wrapping column names with single quotes which makes them string literal.
To fix the problem, just remove the single quotes around the column names:
var sql = "insert into master_dosen(NIP,NAMA_DOSEN,KETERANGAN) ...";
protected void ButtonOk_Click(object sender, EventArgs e)
{
// OracleConnection connect = new OracleConnection();
// connect.ConnectionString = ConfigurationManager.ConnectionStrings["Absensi2.Properties.Settings.Setting"].ConnectionString;
//// SqlConnection connect = new SqlConnection(getConnection());
var sql = "insert into master_dosen(NIP,NAMA_DOSEN,KETERANGAN) values (:NIP, :NAMA_DOSEN, :KETERANGAN)";
using (OracleConnection c = new OracleConnection(ConfigurationManager.ConnectionStrings["Absensi2.Properties.Settings.Setting"].ConnectionString))
{
c.Open();
using (OracleCommand cmd = new OracleCommand(sql, c))
{
cmd.Parameters.Add(":NIP", TextBoxNIP.Text);
cmd.Parameters.Add(":NAMA_DOSEN", TextBoxNamaDosen.Text);
cmd.Parameters.Add(":KETERANGAN", TextBoxKeterangan.Text);
cmd.ExecuteNonQuery();
GridView1.DataBind();
}
c.Close();
}
Try this it will work ,I think you miss the sql insert syntax
I am working on one project for the university and I want to say that I am pretty new in asp.net.
Please find below the code that I am experiencing problems with. The problem is that the update function is not working. In the page load I have some select queries and I load a data from the database into some textareas and textfields. This is working fine - it loads the sample data that I have added manually in my database.
I have buttons that should update the database on click.
This is the code for the buttons:
<a id="A1" class="button" onserverclick="box1_Click" runat="server">
<span>Запази полето <img src="notification-tick.gif" width="12" height="12" /></span>
</a>
This is the code behind:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class admin_Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Loading the data from the database
string DatabaseConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["proekt"].ConnectionString;
string sql1_title = "SELECT title FROM home WHERE id=1";
string sql1_image = "SELECT image FROM home WHERE id=1";
string sql1_text = "SELECT text FROM home WHERE id=1";
string sql2_title = "SELECT title FROM home WHERE id=2";
string sql2_image = "SELECT image FROM home WHERE id=2";
string sql2_text = "SELECT text FROM home WHERE id=2";
string sql3_title = "SELECT title FROM home WHERE id=3";
string sql3_image = "SELECT image FROM home WHERE id=3";
string sql3_text = "SELECT text FROM home WHERE id=3";
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
//box1 data load
SqlCommand cmd1_title = new SqlCommand(sql1_title, conn);
conn.Open();
box1_title.Text = (string)cmd1_title.ExecuteScalar();
conn.Close();
SqlCommand cmd1_image = new SqlCommand(sql1_image, conn);
conn.Open();
box1_img.Text = (string)cmd1_image.ExecuteScalar();
conn.Close();
SqlCommand cmd1_text = new SqlCommand(sql1_text, conn);
conn.Open();
box1_text.InnerText = (string)cmd1_text.ExecuteScalar();
conn.Close();
//box2 data load
SqlCommand cmd2_title = new SqlCommand(sql2_title, conn);
conn.Open();
box2_title.Text = (string)cmd2_title.ExecuteScalar();
conn.Close();
SqlCommand cmd2_image = new SqlCommand(sql2_image, conn);
conn.Open();
box2_img.Text = (string)cmd2_image.ExecuteScalar();
conn.Close();
SqlCommand cmd2_text = new SqlCommand(sql2_text, conn);
conn.Open();
box2_text.InnerText = (string)cmd2_text.ExecuteScalar();
conn.Close();
//box3 data load
SqlCommand cmd3_title = new SqlCommand(sql3_title, conn);
conn.Open();
box3_title.Text = (string)cmd3_title.ExecuteScalar();
conn.Close();
SqlCommand cmd3_image = new SqlCommand(sql3_image, conn);
conn.Open();
box3_img.Text = (string)cmd3_image.ExecuteScalar();
conn.Close();
SqlCommand cmd3_text = new SqlCommand(sql3_text, conn);
conn.Open();
box3_text.InnerText = (string)cmd3_text.ExecuteScalar();
conn.Close();
}
}
protected void box1_Click(object sender, EventArgs e)
{
string DatabaseConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["proekt"].ConnectionString;
string sql1 = "UPDATE home SET title=#title, image=#image, text=#text WHERE Id=1";
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
SqlCommand cmd2 = new SqlCommand(sql1, conn);
cmd2.Parameters.AddWithValue("#title", box1_title.Text);
cmd2.Parameters.AddWithValue("#image", box1_img.Text);
cmd2.Parameters.AddWithValue("#text", box1_text.InnerText);
conn.Open();
cmd2.ExecuteNonQuery();
conn.Close();
}
}
protected void box2_Click(object sender, EventArgs e)
{
}
protected void box3_Click(object sender, EventArgs e)
{
}
}
When I make a change to the title of the box1 and then click the button to update the database it is actually refreshing the page and loading the sample data again and my change is not saved.
Could you please help me with this?. There is no errors nothing.
Thank you guys very much.
PS: I have noticed that when I load the page in my browser and then delete the whole code block for the data load, make a change in the browser in one of the fields and then press the button it s actually updating the database. It is very strange...
This is because you need to take care about the ASP.NET lifecycle.
You need to check if its a PostBack (A postback occurs when you click the button) or not ...
Or you will allways override your data.
protected void Page_Load(object sender, EventArgs e)
{
if (!PostBack)
{
string DatabaseConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["proekt"].ConnectionString;
string sql = "SELECT id,title,image,text FROM home WHERE id in (1,2,3) order by id";
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
conn.Open();
search for datareader -> and use it here ... Save the returning data into
the datareader and filter by ID and if its item/title etc like here and here
conn.Close();
}
}
}
Fisrt, I want to suggest that, in the Page_Load, you only open the sql connection once and execute all the commands while the connection is open and then close it at the end. This will make your page load faster.
Second, you could use asp linkbutton to create a postback when clicked. The syntax should look like this:
<asp:LinkButton ID="A1" runat="server" OnClick="box1_Click">
<span>Запази полето <img src="notification-tick.gif" width="12" height="12" /></span>
</asp:LinkButton>