Dropdown list from database - c#

I cant see the dropdown list I created (click this link for image)
Here is my code in add.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
//ADO.NET
using System.Data;
using System.Data.SqlClient;
using System.IO;
public partial class Admin_Users_Add : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(kmb.GetConnection());
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetCategoryTypes();
}
}
/// <summary>
/// Allows the user to display list of user types
/// from the table Types to the dropdownlist control
/// </summary>
void GetCategoryTypes()
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT CatID, Category FROM Categories";
SqlDataReader dr = cmd.ExecuteReader();
ddlCategoryTypes.DataSource = dr;
ddlCategoryTypes.DataTextField = "Category";
ddlCategoryTypes.DataValueField = "CatID";
ddlCategoryTypes.DataBind();
ddlCategoryTypes.Items.Insert(0, new ListItem("Select one...", ""));
con.Close();
}
}
In database I created 2 tables:
Categories(CatID [PK], Category[FK])
CategoryTypes(Category [PK], Appetizers, Desserts, Beverages)
---- I want to see the "Appetizers, Desserts, Beverages" in the dropdown list which is from database, in my webpage

You need to change the query to:
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT CatID, Appetizers +', '+ Desserts +', '+ Beverages as CatDescription FROM Categories Inner Join CategoryTypes ON Categories.Category = CategoryTypes.Category";
SqlDataReader dr = cmd.ExecuteReader();
ddlCategoryTypes.DataSource = dr;
ddlCategoryTypes.DataTextField = "CatDescription";
ddlCategoryTypes.DataValueField = "CatID";
ddlCategoryTypes.DataBind();
ddlCategoryTypes.Items.Insert(0, new ListItem("Select one...", ""));
con.Close();

Related

Can't retrieve data from database and store into a value

I am currently working on a forum project using a gridview to attached the data to the database. Using SelectedIndexChanged, it will redirect to another page to display the details in labels. However, I am unable to display & there isn't any specific error.
This is my code:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class FAQViewPost : System.Web.UI.Page
{
string _connStr = ConfigurationManager.ConnectionStrings["WingsDrinksDbContext"].ConnectionString;
FAQ faq = null;
string CustQuestionCategory = null;
string CustQuestion = null;
protected void Page_Load(object sender, EventArgs e)
{
string FAQID = Request.QueryString["FAQID"].ToString();
Load(FAQID);
}
protected void Load(string FAQID)
{
DataTable dt = new DataTable();
string queryStr = "SELECT * FROM [FAQ] WHERE FAQID = #FAQID ";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand();
string[] arr = { queryStr };
string allQueries = string.Join(";", arr);
cmd.CommandText = allQueries;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#FAQID", FAQID);
SqlDataAdapter sqlDa = new SqlDataAdapter(cmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
lbl_category.Text = dt.Rows[0]["CustQuestionCategory"].ToString();
lbl_question.Text = dt.Rows[0]["CustQuestion"].ToString();
}
conn.Close();
conn.Dispose();
}
}
I do not know why you are putting the SQL into an array. You only have one statement. Try using just:
DataTable dt = new DataTable();
string queryStr = "SELECT * FROM [FAQ] WHERE FAQID = #FAQID ";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = queryStr;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#FAQID", FAQID);
SqlDataAdapter sqlDa = new SqlDataAdapter(cmd);
sqlDa.Fill(dt);
I presume you have checked that the FAQ table has a record for the id you are sending? Also life would be a bit safer if you used numeric ids.

Unable to display data in gridview in asp.net

I have created a Label control and gridview. Label shows the data but In Gridview data from database does not populate.
Following is my code. No error is received while doing this
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["TestConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("Select BATSMAN_NAME from RUNS_STATS", con);
con.Open();
SqlDataReader dr=cmd.ExecuteReader();
while(dr.Read())
{
Label1.Text = dr.GetString(dr.GetOrdinal("BATSMAN_NAME"));
}
GridView2.DataSource = dr;
GridView2.DataBind();
con.Close();
}
}
}
Use SqlDataAdapter & dataset to fill gridview
SqlCommand cmd = new SqlCommand("Select BATSMAN_NAME from RUNS_STATS", con);
SqlDataAdapter daGrid = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
daGrid.Fill(ds);
GridView2.DataSource = ds.Tables[0];
GridView2.DataBind();
Try disconnected architecture. Incase the following code doesn't work, check if the Query is appropriate.
SqlConnection conobj=new SqlConnection;
SqlCommand cmdobj=new SqlCommand(""Select BATSMAN_NAME from RUNS_STATS", conobj);
SQlDataAdapter sdaobj=new SqlDataAdapter(cmdobj);
DataTable dtobj=new DataTable();
sdaobj.Fill(dtobj);
GridView2.DataSource=dtobj;
GridView2.DataBind();

Program runs without error but not giving desired output

Following program extracts data from SQL Server 2008 tables, applies a simple for loop and counts total number of records. Program compiles and runs successfully without any error but doesn't print the total count of records to the screen. It doesn't print anything.
.cs (code behind) is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;
namespace CountDocs
{
public partial class Home : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnCount_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=MEHDI-PC\\SQLEXPRESS; Initial Catalog=PIMS; Integrated Security=true;");
{
using (SqlCommand cmd = new SqlCommand())
{
String sql = "select * from dbo.Company";
cmd.Connection = con;
cmd.CommandText = sql;
con1.Open();
Int32 Total = 0;
Total = (Int32)cmd1.ExecuteScalar();
Console.WriteLine(Total);
if (con.State == ConnectionState.Open)
{
con.Close();
}
for (int i = 0; i < dt.Rows.Count; ++i)
{
string companyname;
companyname = dt.Rows[i].ItemArray[0].ToString();
SqlConnection con1 = new SqlConnection("Data Source=MEHDI-PC\\SQLEXPRESS; Initial Catalog=PIMS; Integrated Security=true;");
{
using (SqlCommand cmd1 = new SqlCommand())
{
String sql1 = "select Count(*) from dbo.Documents where Src=" + "'" + companyname + "'";
cmd1.Connection = con1;
cmd1.CommandText = sql1;
con.Open();
DataTable dt1 = new DataTable();
Int32 Total = 0;
Total = (Int32)cmd1.ExecuteScalar();
Console.WriteLine(Total);
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}
}
}
}
}
}
}
Since program is not throwing any syntax error, I guess it could be a logical error. Could someone please notice it for me? Thanks in advance.
The system works correct, because if you write dt1.Rows[0].ToString() you did not get the value of the cell. That is because System.Data.DataRowSystem.Data.DataRowSystem.Data.DataRowSystem.Data.DataRowSystem does not override the method ToString().
I think you have to use dt1.Rows[0].ItemArray[3] or dt1.Rows[0]["column name"].ToString();
Hope this helps.

What is the correct syntax for establishing an SQL connection and creating SQL Commands with VS2012?

I'm not really sure where the SqlConnection, SqlCommand and the Open()/Close() goes. I want to use just the single variable cmd throughout the program, hence not using the SqlCommand cmd = new SqlCommand('SELCT * FROM blabla); format.
EDIT: My code below results to the textbox having the text "System.Data.SqlClient.SqlCommand" when i click the button.
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.Data.SqlTypes;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection(#"Data Source=EDIOTH\SQLEXPRESS;
Initial Catalog=Try; Integrated Security=SSPI");
SqlCommand cmd = new SqlCommand();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
con.Open();
cmd.CommandText = "SELECT Pnt_Lname FROM PATIENT WHERE Pnt_ID = 1;";
txtBox1.Text = cmd.ToString();
con.Close();
}
}
}
you can create constant string to hold the connection string and then you can do as below in your button1_Click
you don't need to call the close method of sql connection when you use using block as below
using(SqlConnection con = new SqlConnection(connectionString))
using(SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT Pnt_Lname FROM PATIENT WHERE Pnt_ID = 1";
con.Open();
txtBox1.Text =cmd.ExecuteScalar() as string;
}
And also if you need to read Pnt_Lname from database you better use ExecuteScalar method
You can use this structure. Use using to properly close and dispose of SqlConnection.
Also, you can define the connection string in your config file and use it from there.
using (SqlConnection conn = new SqlConnection(#"Data Source=EDIOTH\SQLEXPRESS;
Initial Catalog=Try; Integrated Security=SSPI"))
{
conn.Open();
SqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT Pnt_Lname FROM PATIENT WHERE Pnt_ID = 1";
txtBox1.Text = (String)command.ExecuteScalar();
}
In case this would be of help to anyone, this is the answer to my question:
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;
namespace Book
{
public partial class frmBook : Form
{
SqlConnection con =
new SqlConnection(#"Data Source=EDIOTH\SQLEXPRESS;
Initial Catalog=XXDB; Integrated Security=SSPI");
SqlCommand cmd;
public frmBook()
{
InitializeComponent();
}
private void frmBook_Load(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("SELECT min(Book_ID) FROM Book;",con);
txtID.Text = cmd.ExecuteScalar().ToString();
cmd = new SqlCommand("SELECT title FROM Book WHERE Book_ID = '"
+ txtID.Text + "'", con);
txtTitle.Text = cmd.ExecuteScalar().ToString();
con.Close();
btnSave.Enabled = false;
}
private void btnNext_Click(object sender, EventArgs e)
{
int count = int.Parse(txtID.Text) + 1;
con.Open();
cmd = new SqlCommand("SELECT title FROM Book WHERE Book_ID = '"
+ count.ToString() +"'", con);
txtTitle.Text = cmd.ExecuteScalar().ToString();
txtID.Text = count.ToString();
con.Close();
}
private void btnNew_Click(object sender, EventArgs e)
{
txtID.Text = "";
txtTitle.Text = "";
txtAuthor.Text = "";
btnNew.Enabled = false;
btnSave.Enabled = true;
}
private void btnSave_Click(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("INSERT INTO Book (Book_ID, Title, Author) " +
"VALUES ('"+ txtID.Text +
"','"+ txtTitle.Text +
"','"+ txtAuthor.Text +"');", con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data saved!");
btnSave.Enabled = false;
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
}
}

How to check if column value is null before inserting data from text box

I am trying to insert data from text box to sql database, but I want to check if the row is empty then insert new value else update the row with the values with sqlcommands in if else condition.
Below is 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.Data.SqlClient;
public partial class CM : System.Web.UI.Page
{
DataSet ds = new DataSet();
SqlDataAdapter da;
SqlCommand cmd;
//DataTable dt;
SqlConnection con = new SqlConnection("server =consulting76\\SQLEXPRESS; database = msdb; Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
da = new SqlDataAdapter();
//("Select * from NOTESMAKER", con);
//da.Fill(ds, "NOTESMAKER");
//dt = ds.Tables["NOTESMAKER"];
}
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
if (DBNull.Value != null)
{
cmd = new SqlCommand("Insert into NOTESMAKER(NOTESMAKER) Values(#text1)",con);
cmd.Parameters.Add(new SqlParameter("#text1", SqlDbType.NText)).Value = TextBox1.Text;
da.InsertCommand = cmd;
cmd.ExecuteNonQuery();
}
else
{
cmd = new SqlCommand("Update NOTESMAKER set NOTESMAKER = #text1)",con);
cmd.Parameters.Add(new SqlParameter("#text1", SqlDbType.NText)).Value = TextBox1.Text;
da.UpdateCommand = cmd;
cmd.ExecuteNonQuery();
}
con.Close();
}
}
if you don't know how to fired a select query, have a look here
select * from tablename where columnName is not null
fill sqldataadapter from your query eg
if dataset count is zero then you may proceed with insert operation else update.
if (ds.table[0].rows.count==0)//insert
{
}
else// update
}
You can do it this way. ExecuteNonQuery() returns the number of affected rows, so if insert returns 0, it means that there was nothing to update. Hence you need to insert a row.
cmd = new SqlCommand("Update NOTESMAKER set NOTESMAKER = #text1)",con);
cmd.Parameters.Add(new SqlParameter("#text1", SqlDbType.NText)).Value = TextBox1.Text;
int affectedRows = cmd.ExecuteNonQuery();
if (affectedRows == 0)
{
cmd = new SqlCommand("Insert into NOTESMAKER(NOTESMAKER) Values(#text1)",con);
cmd.Parameters.Add(new SqlParameter("#text1", SqlDbType.NText)).Value = TextBox1.Text;
cmd.ExecuteNonQuery();
}

Categories

Resources