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";
Related
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.
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 LMS
{
public partial class Member : Form
{
public Member()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
CreateNew();
}
void CreateNew()
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
textBox5.Text = "";
comboBox1.Text = "";
comboBox2.Text = "";
comboBox3.Text = "";
Connection con = new Connection();
SqlDataAdapter sda = new SqlDataAdapter("Proc_member", con.ActiveCon());
sda.SelectCommand.CommandType = CommandType.StoredProcedure;
DataTable dt = new DataTable();
sda.Fill(dt);
textBox1.Text = dt.Rows[0][0].ToString();
textBox2.Focus();
}
}
}
I can't get any value from this procedure. I have used the same code with different procedure names in a different form (and I have saved all of them). It works perfectly but in other forms it keeps generating this error. I'm just a beginner, so please answer in the simplest way possible.
Your data table is empty , you need to execute command before
using (SqlCommand command = new SqlCommand(sSql, con))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
DataTable dtSchema = reader.GetSchemaTable();
for (int i = 0; i < reader.FieldCount; i++)
{
var fieldVal = reader.GetValue(i).ToString();
}
}
}
}
I'm trying to insert new rows to an Access database in C#. The code compiles and supposedly inserts new data to the database, but there is no new data after the datagridview update. Also no new data on the database itself.
Sorry, I'm new with this, could someone help me?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplicaction1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
OleDbConnection connect = new OleDbConnection();
private void Form1_Load(object sender, EventArgs e)
{
this.articulosTableAdapter.Fill(this.inventarioDataSet.Articulos);
}
private void UpdateTable()
{
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Kudox\Desktop\Inventario.accdb";
connect.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connect;
string query = "SELECT * from Articulos";
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
connect.Close();
}
private void btnInsertar_Click(object sender, EventArgs e)
{
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Kudox\Desktop\Inventario.accdb";
string Nombre;
int Cantidad, CostoPU, Importancia, CostoTO;
try
{
Nombre = txtNombre.Text;
Cantidad = int.Parse(txtCantidad.Text);
CostoPU = int.Parse(txtCosto.Text);
Importancia = int.Parse(cmbImportancia.SelectedItem.ToString());
CostoTO = CostoPU * Cantidad;
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Kudox\Desktop\Inventario.accdb";
OleDbCommand cmd = new OleDbCommand("INSERT into Articulos(NombreArticulo, CostoPorUnidad, CantidadDeArticulos, Importancia, CostoTotal) values('"+Nombre+"','" + CostoPU +"','" + Cantidad +"','" + Importancia +"','" + CostoTO +"')");
MessageBox.Show("Articulo agregado");
UpdateTable();
}
catch(Exception err)
{
MessageBox.Show(err.Message);
}
}
}
}
After setting your datasource, you need to databind, so within your UpdateTable() procedure, after dataGridView1.DataSource = dt;, add:
dataGridView1.DataBind();
As far as your insert command, you need to execute it at some point (probably right after your OleDbCommand cmd = ... line), something like:
cmd.ExecuteNonQuery();
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.
I am a beginner programer.
I wrote following code that must do the following steps:
1-connect to my dataset that has two fields :UserID,TrackID (2916 fields)
2-Read the dataset line by line and put the UserId of each recored to a url(instead of ).
3-Search through the Url
4-if it finds the TrackId which is related to UserId, add 1 to counter.
I am not sure about the Logic of the program,Did I write it correct?
Thank you
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Net;
namespace test2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\hidden.accdb";
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "Select * from hidden.accdb";
DataTable dt = new DataTable();
//To read data from dataset
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = cmd;
//Store the UserID
adapter.Fill(dt);
int UserID=0,TrackID=0;
int counter=0;
foreach(DataRow row in dt.Rows)
{
string url = "http://abcd/<userid>?groups=<userid>";
var test = url.Replace("<userid>", Convert.ToString(row.UserID));
System.Diagnostics.Process.Start(url);
string client = (new WebClient()).DownloadString("http://abcd/UserID?groups=UserID");
if (client.Contains(Convert.ToString(TrackID)))
{
counter++;
}
int ave = counter / 2916;
MessageBox.Show("Average" + counter);
}
conn.Close();
}
}
}
You can't access your UserId in DataRow like this:
row.UserID
You should use indexer, you can access it by column name or column index:
var test = url.Replace("<userid>", Convert.ToString(row["UserID"]));
I don't see another mistake in your code except that.