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

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.

Related

How do I reset/reload/unload my DataGridView?

I have this problem while working on a problem on my assignment/homework. I wanted to load multiple data table from my SQL database into multiple datagridviews but when i click on another tab (with SelectedIndexChanged on TabControl) the column of the older loaded table still there. I just want each tab to show specific tables(columns).
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.Common;
using System.Data.OleDb;
using System.Data.Odbc;
using System.Data.SqlClient;
using System.Data.SqlTypes;
namespace assignment2Database
{
public partial class Form1 : Form
{
SqlConnection connection;
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
DataTable table = new DataTable();
string str = #"Data Source=DESKTOP-S1O2044\SQLEXPRESS;Initial Catalog=ElectroShopDB;Integrated Security=True";
private void tabSupplier_SelectedIndexChanged(object sender, EventArgs e)
{
if (tabControl.SelectedIndex == 0)
{
connection = new SqlConnection(str);
connection.Open();
loadCatalogue();
}
else if (tabControl.SelectedIndex == 1)
{
connection = new SqlConnection(str);
connection.Open();
loadSupplier();
}
}
void loadCatalogue()
{
command = connection.CreateCommand();
command.CommandText = "select catalogueID,catalogueName from Catalogue";
adapter.SelectCommand = command;
table.Clear();
adapter.Fill(table);
dgvCatalogue.DataSource = table;
}
private void Form1_Load(object sender, EventArgs e)
{
connection = new SqlConnection(str);
connection.Open();
loadCatalogue();
}
void loadSupplier()
{
command = connection.CreateCommand();
command.CommandText = "select supplierID,supplierName from Supplier";
adapter.SelectCommand = command;
table.Clear();
adapter.Fill(table);
dgvSupplier.DataSource = table;
}
I want the SelectedIndexChanged event when triggered on each tabs on tab control to not have the old columns of the previous datagridview appear on the new loaded datagridview. Or I just want each individual datagridview to hold a table from my SQL database.
Unbind the first datasource and then rebind:
dgvSupplier.DataSource = null;
dgvSupplier.DataSource = table;
This will kick out all the older columns and only populate the ones you need. Do this in every method you use to repopulate your grid:
void loadCatalogue()
{
command = connection.CreateCommand();
command.CommandText = "select catalogueID,catalogueName from Catalogue";
adapter.SelectCommand = command;
table.Clear();
adapter.Fill(table);
dgvSupplier.DataSource = null;
dgvCatalogue.DataSource = table;
}
void loadSupplier()
{
command = connection.CreateCommand();
command.CommandText = "select supplierID,supplierName from Supplier";
adapter.SelectCommand = command;
table.Clear();
adapter.Fill(table);
dgvSupplier.DataSource = null;
dgvSupplier.DataSource = table;
}
Like so.
Edit:
Additionally, you can create a new adapter in your population methods to empty them:
void loadCatalogue()
{
SqlDataAdapter catalogueAdapter = new SqlDataAdapter();
command = connection.CreateCommand();
command.CommandText = "select catalogueID,catalogueName from Catalogue";
catalogueAdapter.SelectCommand = command;
table.Clear();
catalogueAdapter.Fill(table);
dgvSupplier.DataSource = null;
dgvCatalogue.DataSource = table;
}
void loadSupplier()
{
SqlDataAdapter supplierAdapter = new SqlDataAdapter();
command = connection.CreateCommand();
command.CommandText = "select supplierID,supplierName from Supplier";
supplierAdapter.SelectCommand = command;
table.Clear();
supplierAdapter.Fill(table);
dgvSupplier.DataSource = null;
dgvSupplier.DataSource = table;
}

AddWithValue not working on SqlCommand query

The method GetData in the following code works as long as I use valid column names, however, when trying to use a variable (query string parameter value) in the SQL query, I get empty results.
I am assuming I am not using the .AddWithValue method properly. Am I not writing the SQL command properly, or does it have something to do with the code placement of the .AddWithValue method call? Or something else I am missing?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.AspNet.FriendlyUrls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
namespace Koobek
{
public partial class WebForm6 : System.Web.UI.Page
{
string cat = "";
string getcat = "";
protected void Page_Load(object sender, EventArgs e)
{
var segments = Request.GetFriendlyUrlSegments();
int count = segments.Count;
if (segments.Count > 0)
cat = segments[0];
string getcat = Request.QueryString["cat"];
ListView1.DataSource = this.GetData();
ListView1.DataBind();
System.Diagnostics.Debug.WriteLine(getcat);
}
private DataSet GetData()
{
string conString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string query = #"SELECT DISTINCT newcatdisplay, newclassdisplay, newclass, newcat FROM ejn_series WHERE newcat = #getcat ORDER BY newclassdisplay";
SqlCommand cmd = new SqlCommand(query);
cmd.Parameters.AddWithValue("#getcat", getcat);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
if (ds.Tables[0].Rows.Count == 0)
{
System.Console.WriteLine("empty");
}
return ds;
}
}
}
}
}
}
You cannot add parameters to a text sql statement. Do this:
string query = #"SELECT DISTINCT newcatdisplay, newclassdisplay,
newclass, newcat FROM ejn_series WHERE newcat = '" + getcat + "' " +
"ORDER BY newclassdisplay";

How to save data from local sdf database into text file?

Is there any possibility to save data from local sdf database into text file in C# ? I don't have any idea how to do it and unfortunettly I don't have a lot of time.. each row of the database must be in new line of text file
You must do it manually (i.e. by code). MS SQL CE does not provide the import/export features that the SQL Server editions do.
this is from an old project of mine it works. just change the name of the table "tableProduit" with the name of your choice. if you run into problems ask ....
using System;
using System.Data.SqlServerCe;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using System.Data;
namespace app
{
class Connexion
{
SqlCeConnection conn;
string connectionString;
string chemin;
public Connexion(string path,string password)
{
this.chemin = path;
connectionString = string.Format("DataSource={0}", this.chemin + ";Password="+password);
conn = new SqlCeConnection(connectionString);
}
public bool isConnected()
{
try
{
conn.Open();
}catch(SqlCeException e){
MessageBox.Show(e.ToString());
return false;
}
bool temp = false;
SqlCeDataReader dr;
SqlCeCommand cmd = new SqlCeCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM tableProduit";
dr = cmd.ExecuteReader();
if (dr.Read())
{
temp = true;
}
else
{
temp = false;
}
dr.Close();
conn.Close();
return temp;
}
public void writeData(string filepath,string filetype)
{
conn.Open();
SqlCeDataReader dr;
SqlCeCommand cmd = new SqlCeCommand();
SqlCeDataAdapter adpt = new SqlCeDataAdapter();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM tableProduit";
dr = cmd.ExecuteReader();
adpt.SelectCommand = cmd;
if (filetype == "txt")
{
TextWriter writer = new StreamWriter(filepath);
while (dr.Read())
{
writer.WriteLine(dr["codeBarre"] + ":" + dr["qte"]);
}
writer.Close();
}
else
{
//Create the data set and table
DataSet ds = new DataSet("New_DataSet");
DataTable dt = new DataTable("New_DataTable");
//Set the locale for each
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
adpt.Fill(dt);
ds.Tables.Add(dt);
}
dr.Close();
conn.Close();
}
}
}
Edit : forget about the fileds writer.WriteLine(dr["codeBarre"] + ":" + dr["qte"]); change them to the names of your fields.good luck

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();
}

SQLCommand syntax error

I am writing to request some help on my c# syntax. I keep getting syntax in "sda.Fill(dt);" and I can not figure out the reason why.
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;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string query = "select distinct Price_type from Price";
DataTable dt = GetData(query);
ddlPrice.DataSource = dt;
ddlPrice.DataTextField = "Price_type";
ddlPrice.DataValueField = "Price_type";
ddlPrice.DataBind();
ddlPrice2.DataSource = dt;
ddlPrice2.DataTextField = "Price_type";
ddlPrice2.DataValueField = "Price_type";
ddlPrice2.DataBind();
ddlPrice2.Items[1].Selected = true;
}
}
protected void Compare(object sender, EventArgs e)
{
string query = string.Format("select price, date from Price where Price_type = '{0}' order by date)", ddlPrice.SelectedItem.Value);
DataTable dt = GetData(query);
string[] x = new string[dt.Rows.Count];
decimal[] y = new decimal[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
x[i] = dt.Rows[i][0].ToString();
y[i] = Convert.ToInt32(dt.Rows[i][1]);
}
LineChart1.Series.Add(new AjaxControlToolkit.LineChartSeries { Name = ddlPrice.SelectedItem.Value, Data = y });
query = string.Format("select price, date from Price where Price_type = '{0}' order by date)", ddlPrice2.SelectedItem.Value);
dt = GetData(query);
y = new decimal[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
x[i] = dt.Rows[i][0].ToString();
y[i] = Convert.ToInt32(dt.Rows[i][1]);
}
LineChart1.Series.Add(new AjaxControlToolkit.LineChartSeries { Name = ddlPrice2.SelectedItem.Value, Data = y });
LineChart1.CategoriesAxis = string.Join(",", x);
LineChart1.ChartTitle = string.Format("{0} and {1} Order Distribution", ddlPrice.SelectedItem.Value, ddlPrice2.SelectedItem.Value);
LineChart1.Visible = true;
}
private static DataTable GetData(string query)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["bwic testConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
date might be a reserved keyword, depending of the version you use. Write [date] instead. And this
"select price, date from Price where Price_type = '{0}' order by date)"
should be
"select price, date from Price where Price_type = '{0}' order by date"
You can try with this code
using (var con = new SqlConnection(constr))
{
using (var cmd = new SqlCommand(query))
{
using (var sda = new SqlDataAdapter())
{
con.Open();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
There's nothing syntactically wrong with your GetData() method as shown in your original post. You might try commenting out the entire body of the method and then start uncommenting things one at a time to isolate the actual problem.
But it apparently seems that you don't have a syntax error: you have invalid SQL. The SQL you are trying to execute is:
select price, date from Price where Price_type = '{0}' order by date)
It has two things wrong with it:
The closing (right) parenthesis at the end is your syntax error, and
the parameter should not be enclosed in quotes.
Your SQL should look something like
select price, date from Price where Price_type = {0} order by date
Your method should look something like this:
private static DataTable GetData1( string query , string p0 )
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["bwic testConnectionString"].ConnectionString;
using ( SqlConnection con = new SqlConnection( constr ) )
using ( SqlCommand cmd = con.CreateCommand() )
using ( SqlDataAdapter sda = new SqlDataAdapter(cmd) )
{
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
SqlParameter p = new SqlParameter() ;
p.Value = p0Value ;
cmd.Parameters.Add( p ) ;
con.Open();
sda.Fill( dt );
con.Close();
}
return dt;
}
Don't forget to use brackets twice - in SELECT clause and in ORDER BY clause too.
in your code bolck as below
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
change it to
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
con.Open();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
The problem here is that you havent opened any connection before filling.
You haven't opened a connection anywhere. You must open the connection before you can use it.
If your whole class code is really this, you are missing a closing } at the end of the file for the
public partial class Default2 : System.Web.UI.Page
{
declaration.

Categories

Resources