how to pass Sql parameter - c#

This error will come in my code Procedure or function 'gridalldata' expects parameter '#order_no', which wast not supplied. I am sending parameter to procedure like below
try
{
con.Open();
SqlCommand cmd = new SqlCommand("gridalldata", con);
cmd.Parameters.Add("#order_no", SqlDbType.NVarChar).Value = txt_orderno.Text;
SqlDataReader dr = cmd.ExecuteReader();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (dr.HasRows)
{
dr.Read();
dataGridView1.Rows[i].Cells[0].Value = dr[0].ToString();
dataGridView1.Rows[i].Cells[2].Value = dr[2].ToString();
dataGridView1.Rows[i].Cells[3].Value = dr[3].ToString();
dataGridView1.Rows[i].Cells[4].Value = dr[4].ToString();
dataGridView1.Rows[i].Cells[5].Value = dr[5].ToString();
dataGridView1.Rows[i].Cells[6].Value = dr[6].ToString();
dataGridView1.Rows[i].Cells[7].Value = dr[7].ToString();
dataGridView1.Rows[i].Cells[8].Value = dr[8].ToString();
dataGridView1.Rows[i].Cells[9].Value = dr[9].ToString();
dataGridView1.Rows[i].Cells[10].Value = dr[13].ToString();
dataGridView1.Rows[i].Cells[11].Value = dr[12].ToString();
}
}
dr.Close();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
How To Fix This

Use cmd.CommandType = CommandType.StoredProcedure; to execute stored procedure.

Try This:
Try
{
con.Open();
string order= txt_orderno.Text;
SqlCommand cmd = new SqlCommand("gridalldata", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#order_no", SqlDbType.NVarChar).Value=order;
SqlDataReader dr = cmd.ExecuteReader();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (dr.HasRows)
{
dr.Read();
dataGridView1.Rows[i].Cells[0].Value = dr[0].ToString();
dataGridView1.Rows[i].Cells[2].Value = dr[2].ToString();
dataGridView1.Rows[i].Cells[3].Value = dr[3].ToString();
dataGridView1.Rows[i].Cells[4].Value = dr[4].ToString();
dataGridView1.Rows[i].Cells[5].Value = dr[5].ToString();
dataGridView1.Rows[i].Cells[6].Value = dr[6].ToString();
dataGridView1.Rows[i].Cells[7].Value = dr[7].ToString();
dataGridView1.Rows[i].Cells[8].Value = dr[8].ToString();
dataGridView1.Rows[i].Cells[9].Value = dr[9].ToString();
dataGridView1.Rows[i].Cells[10].Value = dr[13].ToString();
dataGridView1.Rows[i].Cells[11].Value = dr[12].ToString();
}
}
dr.Close();
con.Close();
}

using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
String orderNo=txt_orderno.Text;
// Am assuming gridalldata is your SP
SqlCommand cmd= new SqlCommand(gridalldata, connection);
cmd.CommandType=CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#order_no", orderNo);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
// Code
}
}
The using statement makes sure the connection is closed after use
Also You should bind Your Datagridview like this
Public DataTable FillDataGrid(string orderID)
{
SqlCommand cmd = new SqlCommand("gridalldata", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#order_no", orderNo);
SqlDataAdapter dap = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
dap.Fill(ds);
return ds.Tables[0];
}
Datatable dt=FillDataGrid(txt_orderno.Text);
DataGridVIew1.DataSource=dt;

Related

Problem , Converting DBNull! Please help me from error object cannot be cast from DBNull to other type in C# with following code

string connstr = "connstr";
SqlConnection connection = new SqlConnection(#"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True;Application Name=Aung");
connection.Open();
SqlCommand cmdCount = new SqlCommand("SELECT COUNT(*) FROM Mini_table WHERE Item = #Item", connection);
cmdCount.Parameters.AddWithValue("#Item", cbox2.SelectedItem.ToString());
int count = (int)cmdCount.ExecuteScalar();
int i = 0;
if (count > 0)
{
SqlCommand command = new SqlCommand("SELECT Qty FROM Mini_table WHERE Item = #Item", connection);
command.Parameters.AddWithValue("#Item", cbox2.SelectedItem.ToString());
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
i = Convert.ToInt32(reader["Qty"]);
}
}
SqlCommand updatecmd = new SqlCommand("Update Mini_table set Qty=#Qty, Date=#Date where Item=#Item", connection);
updatecmd.Parameters.AddWithValue("#Qty", i + Nd2.Value);
updatecmd.Parameters.AddWithValue("#Date", DateTime.Now);
updatecmd.Parameters.AddWithValue("#Item", cbox2.SelectedItem.ToString());
updatecmd.ExecuteNonQuery();
dgv2.DataSource = null;
MessageBox.Show("Update successfully");
}
else
{
SqlCommand insertcmd = new SqlCommand("insert into Mini_table(Item,Qty,Date)values(#Item,#Qty,#Date)", connection);
insertcmd.Parameters.AddWithValue("#Item", cbox2.SelectedItem.ToString());
insertcmd.Parameters.AddWithValue("#Qty", Nd2.Value);
insertcmd.Parameters.AddWithValue("#Date", DateTime.Now);
insertcmd.ExecuteNonQuery();
dgv2.DataSource = null;
MessageBox.Show("Insert successfully");
}
connection.Close();
}
{
string connstr = "connstr";
SqlConnection connection = new SqlConnection(#"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True;Application Name=Aung");
connection.Open();
SqlCommand cmdCount = new SqlCommand("SELECT COUNT(*) FROM Stotal_table WHERE Item = #Item", connection);
cmdCount.Parameters.AddWithValue("#Item", cbox2.SelectedItem.ToString());
int count = (int)cmdCount.ExecuteScalar();
int i = 0;
if (count > 0)
{
SqlCommand command = new SqlCommand("SELECT MiniBar FROM Stotal_table WHERE Item = #Item", connection);
command.Parameters.AddWithValue("#Item", cbox2.SelectedItem.ToString());
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
i = Convert.ToInt32(reader["MiniBar"]);
{
}
}
}
SqlCommand updatecmd = new SqlCommand("Update Stotal_table set MiniBar=#MiniBar, where Item=#Item", connection);
updatecmd.Parameters.AddWithValue("#MiniBar", i + Nd2.Value);
updatecmd.Parameters.AddWithValue("#Item", cbox2.SelectedItem.ToString());
updatecmd.ExecuteNonQuery();
}
else
{
SqlCommand insertcmd = new SqlCommand("insert into Stotal_table(Item,MiniBar)values(#Item,#MiniBar)", connection);
insertcmd.Parameters.AddWithValue("#Item", cbox2.SelectedItem.ToString());
insertcmd.Parameters.AddWithValue("#MiniBar", Nd2.Value);
insertcmd.ExecuteNonQuery();
}
connection.Close();
Before assigning the reader value to int, first check if the reader object is DBNull
for example
if (reader["MiniBar"] != DBNull.Value)
{
i = Convert.ToInt32(reader["MiniBar"]);
}
else
{
i = 0; // or -1
}

Winform DataGridView still shows data after final update

I'm developing a winform application using C#.net, using DataGridView to display the data, but after the last update, the DataGridView returns 1 last row, but i want my DataGridView to return a blank row or just show the header only...
nb: Before the update JmlKirimK value is 1.
try
{
con.Close();
con.Open();
MySqlCommand cmd = new MySqlCommand("Select PasienID, NoHP, JmlKirimK from datapasien where JmlKirimK ='1' AND StatusDiabetes='Ya'", con);
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
con.Close();
con.Open();
nohp = Convert.ToString(dr[1]);
idpasien = Convert.ToString(dr[0]);
jml = Convert.ToString(dr[2]);
Cursor.Current = Cursors.WaitCursor;
if (objclsSMS.sendMsg(this.port2, nohp, this.txtisi.Text))
{
MySqlCommand cmd3 = new MySqlCommand("UPDATE datapasien SET JmlKirimK='2' Where PasienID='" + idpasien.Trim() + "'", con);
cmd3.ExecuteNonQuery();
terkirim = terkirim + 1;
showgridkirimulang();
}
else
{
tdkterkiri = tdkterkiri + 1;
}
showgridkirimreset();
}
con.Close();
alert.ContentImage = SmsGatewayProlanis.Properties.Resources.Warning1;
alert.CaptionText = "Status";
alert.ContentText = "Pesan Terkirim = " + terkirim + ", Pesan Tidak Terkirim = " + tdkterkiri;
alert.Show();
}
catch (Exception ex)
{
alert.ContentImage = SmsGatewayProlanis.Properties.Resources.Warning1;
alert.CaptionText = "Status";
alert.ContentText = ex.Message;
alert.Show();
ErrorLog(ex.Message);
}
This is my DataGridView code
private void showgridkirimulang()
{
con.Close();
con.Open();
MySqlCommand cmd = new MySqlCommand("SELECT NamaPasien, RiwayatPenyakit, AlamatPasien, UmurPasien, Jeniskelamin, NoHP, JmlKirimK, StatusDiabetes FROM datapasien WHERE JmlKirimK=1 AND StatusDiabetes='Ya'", con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
cmd.ExecuteNonQuery();
if (ds.Tables[0].Rows.Count > 0)
{
gridkirimulang.DataSource = ds.Tables[0];
gridkirimulang.Columns[0].HeaderText = "Nama Pasien";
gridkirimulang.Columns[1].HeaderText = "Riwayat Penyakit";
gridkirimulang.Columns[2].HeaderText = "Alamat Pasien";
gridkirimulang.Columns[3].HeaderText = "Umur Pasien";
gridkirimulang.Columns[4].HeaderText = "Jenis Kelamin";
gridkirimulang.Columns[5].HeaderText = "No. HP";
gridkirimulang.Columns[6].HeaderText = "Jumlah Pesan Terkirim";
gridkirimulang.Columns[7].HeaderText = "Status Diabetes";
gridkirimulang.MasterGridViewTemplate.BestFitColumns();
}
con.Close();
}

AjAX Rating Control storing and fetching from database using repeater in asp.net c# i

I got error:
Specified cast is not valid.
I need to repeat every user already rating star from database how to get rating from db. Here how to take rating from database.
Here is the stored procedure:
ALTER PROCEDURE [dbo].[sp_comments]
(
#eid int
)
AS
BEGIN
declare #sql varchar(max)
SET NOCOUNT ON;
select #sql='select g.username,dbo.fn_username(g.updation) as updation,
c.comment_id,c.id,c.comments,c.commented_by,c.mail,c.date,c.rating_star
from comments c
inner join tbl_data as g on g.id=c.id
WHERE c.id=''' +CONVERT(VARCHAR(50),#eid) +''' order by comment_id desc'
exec(#sql)
print(#sql)
END
Here is my asp.net Design page:
<asp:Rating ID="user_rating" runat="server" CurrentRating='<%#Eval("rating_star")%>' RatingDirection="LeftToRightTopToBottom" StarCssClass="ratingStar" WaitingStarCssClass="SavedRatingStar" FilledStarCssClass="FilledRatingStar"
EmptyStarCssClass="EmptyRatingStar" AutoPostBack="true"></asp:Rating>
Here is the code behind - C# of the page
protected void Button1_Click(object sender, EventArgs e)
{
if (Request.QueryString["id"] != null)
{
int id;
id = Convert.ToInt32(Request.QueryString["id"].ToString());
con = new SqlConnection(str);
con.Open();
cmd = new SqlCommand("sp_usercomment", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#mail", mail_by.Text);
cmd.Parameters.AddWithValue("#comments", comments.Text);
cmd.Parameters.AddWithValue("#name", name_by.Text);
cmd.Parameters.AddWithValue("#updated_name", Convert.ToInt32(Request.Cookies["userid"].Value));
cmd.Parameters.AddWithValue("#eid",id);
cmd.Parameters.AddWithValue("#rating",SqlDbType.Int).Value=rating.CurrentRating;
cmd.ExecuteNonQuery();
con.Close();
Label2.Visible = true;
Label2.Text = "Thanks for your valuable feedback";
mail_by.Text = "";
comments.Text = "";
name_by.Text= "";
getcomments();
}
}
void getcomments()
{
con = new SqlConnection(str);
con.Open();
cmd = new SqlCommand("sp_comments", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#eid", Request.QueryString["id"].ToString()));
da=new SqlDataAdapter(cmd);
dt = new DataTable();
da.Fill(dt);
con.Close();
comment_label.Text = "View " + dt.Rows.Count.ToString() + " Comments";
if (dt.Rows.Count > 0)
{
DataRow dr=dt.Rows[0];
repeat.DataSource = dt.DefaultView;
repeat.DataBind();
review_panel.Visible = true;
product = dr["username"].ToString();
}
else
{
review_panel.Visible = false;
}
}
try this,
con = new SqlConnection(str);
con.Open();
cmd = new SqlCommand("sp_comments", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#eid",Request.QueryString["id"].ToString()));
da=new SqlDataAdapter(cmd);
dt = new DataTable();
da.Fill(dt);
con.Close();
DataTable dtCloned = dt.Clone();
dtCloned.Columns[3].DataType = typeof(Int32);
foreach (DataRow row in dt.Rows)
{
dtCloned.ImportRow(row);
}
repeat.DataSource = dtCloned;
repeat.DataBind();
note : here "3" in dtCloned.Columns[3].DataType will be your column number where rating_star columns is coming in your datatable.

c# ado.net sqlparameter fails

I am passing sqlparameter in localize language (Persian) from c# but no rows retrieves. Database already collate for persioan_100_ci_ai and tables are collate database_default
SqlCommand cmd = new SqlCommand();
DataTable dt = new DataTable();
SqlDataReader dr = default(SqlDataReader);
dt.TableName = "temp";
try {
if (!(conn.State == ConnectionState.Closed))
conn.Close();
if (conn.State == ConnectionState.Closed)
conn.Open();
cmd.Connection = conn;
string qry = "Select * from users WHERE [Name]=#UserName AND [Pwd]=#Password";
cmd.commandtext = qry;
cmd.Parameters.Add("#UserName", SqlDbType.NVarChar, 50).Value = "ادمین";
cmd.Parameters.Add("#Password", SqlDbType.NVarChar, 50).Value = "ادمین";
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows) {
dt.Load(dr);
}
return dt;
} catch (Exception ex) {
return null;
} finally {
dt = null;
cmd.Connection = null;
cmd.Parameters.Clear();
cmd.Dispose();
}
It works in SSMS
declare #UserName nvarchar(50) = 'ادمين'
declare #Password nvarchar(50)= 'ادمين'
select * from Users where [name]=#UserName and [Pwd] = #Password
It even works when I am embedding variables in query instead of parameter
SqlCommand cmd = new SqlCommand();
DataTable dt = new DataTable();
SqlDataReader dr = default(SqlDataReader);
string pLoginName = "ادمین";
string pPassword = "ادمین";
dt.TableName = "temp";
try {
if (!(conn.State == ConnectionState.Closed))
conn.Close();
if (conn.State == ConnectionState.Closed)
conn.Open();
cmd.Connection = conn;
string qry = "Select * from users WHERE [Name]='" + pLoginName + "' AND [Pwd]='" + pPassword + "'";
cmd.CommandText = qry;
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows) {
dt.Load(dr);
}
return dt;
} catch (Exception ex) {
return null;
} finally {
dt = null;
cmd.Connection = null;
cmd.Parameters.Clear();
cmd.Dispose();
}
Cannot figure out where I am wrong.
Please, if any one can point out.
I don't have any problems, I add both values to my test database. Here is the sample code
// Code in BO logic method
string email = "ادمین";
string password = "ادمین";
SqlCommand cmd = new SqlCommand(#"SELECT * FROM Register WHERE Email=#Email AND Deleted=0 AND Password=#Pass");
cmd.Parameters.AddWithValue(#"Email", email.Trim());
cmd.Parameters.AddWithValue(#"Pass", password.Trim());
DataSet dst = Varmebaronen.AppCode.DA.SqlManager.GetDataSet(cmd);
//DataAccess Methods !
public static DataSet GetDataSet(SqlCommand cmd)
{
return GetDataSet(cmd, "Table");
}
public static DataSet GetDataSet(SqlCommand cmd, string defaultTable)
{
SqlConnection conn = GetSqlConnection(cmd);
try
{
DataSet resultDst = new DataSet();
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(resultDst, defaultTable);
}
return resultDst;
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
DataSet had one record, try to use AddWithValue. If again nothing happen the problem is not in the parameters !
P.S Don't use one static connection, application pool is your friend !
Try seperating out the parameter and value assignment like below:
// Create the parameter objects as specific as possible.
cmd.Parameters.Add("#UserName", System.Data.SqlDbType.NVarChar, 50);
cmd.Parameters.Add("#Password", System.Data.SqlDbType.NVarChar, 50);
// Add the parameter values. Validation should have already happened.
cmd.Parameters["#UserName"].Value = "ادمین";
cmd.Parameters["#Password"].Value = "ادمین";
Try to use this:
cmd.Parameters.Add(new SqlParameter("#Password", "ادمین"));
EDIT:
Lets try a different way. If you're up for some re-coding. I will post an example from an old college project that works. It's essentially the same concept. May not be the best way but it works...
I used a DataAdapter, a DataSet, and a GridView control on an .aspx page. You tagged ASP.net, but I am not sure what you're trying to use to display the data.
string selectsql2 = "SELECT * FROM [dbo].Event_View WHERE (EventName LIKE '%' + #EventName + '%')";
SqlConnection connect2 = new SqlConnection(connectionstring2);
SqlCommand cmd = new SqlCommand(selectsql2, connect2);
SqlParameter pm = new SqlParameter("#EventName", txtEvents.Text);
cmd.Parameters.Add(pm);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds2 = new DataSet();
adapter.Fill(ds2);
gvEvents.DataSource = ds2;
gvEvents.DataBind();

Get number of tables from ms access

i'm developing a program for a cachier using c#. The program using ms access for the database. for somehow, the database does not enterd into the table. where is my problem? here is the code:
private void buttonCloseCart_Click(object sender, EventArgs e)
{
connect.ConnectionString = connString;
connect.Open();
OleDbCommand cmd1 = new OleDbCommand("INSERT INTO ReceiptItem (ItemID, Quantity, UnitPrice) VALUES (#itemID, #temp_item_quantity, #temp_item_price)", connect);
cmd1.Parameters.Add("#temp_item", OleDbType.Char, 20);
cmd1.Parameters.Add("#temp_item_quantity", OleDbType.Integer, 20);
cmd1.Parameters.Add("#temp_item_price", OleDbType.Double, 20);
cmd1.Parameters.Add("#cart_sum", OleDbType.Double, 20);
cmd1.Parameters.Add("#itemID", OleDbType.Integer, 20);
for (int i = 0; i < baught_items.Count; i++)
{
/*Set temporary reference to the objects located on the List*/
string temp_item = baught_items[i].ToString();
int temp_item_quantity = baught_items_quantity[i];
double temp_item_price = baught_items_price[i];
double temp_total_item_price = total_items_price[i];
/*Set the connection to the CachierPro DataBase*/
OleDbConnection myconnection = new OleDbConnection(connect.ConnectionString);
myconnection.Open();
//OleDbConnection myconnection1 = new OleDbConnection(connect.ConnectionString);
//myconnection1.Open();
/*********************************************/
/*This Action get the Item Name directly from the database according to the item name in the cart*/
//OleDbConnection dataConnection = new OleDbConnection();
//dataConnection.ConnectionString = connString;
//dataConnection.Open();
//OleDbConnection oledbConn = new OleDbConnection(connString);
//oledbConn.Open();
//OleDbCommand myCommand1 = new OleDbCommand();
//myCommand1.Connection = myconnection1;
//myCommand1.Connection.Close();
OleDbCommand cmd = new OleDbCommand("SELECT [ItemID] FROM ItemsList WHERE [ItemName] = " + "'"+temp_item +"'" , connect);
OleDbDataReader dataReader = cmd.ExecuteReader();
if (dataReader.Read()) { }
int itemID = dataReader.GetInt32(0);
/********************************************/
/*Initialize the Command ment for the Query*/
OleDbCommand myCommand = new OleDbCommand();
myCommand.Connection = myconnection;
//myCommand.ExecuteNonQuery();
myCommand.Connection.Close();
//dataConnection.Close();
//oledbConn.Close();
myconnection.Close();
dataReader.Close();
/*Enter the first query*/
if (connect.State == ConnectionState.Open)
{
try
{ int addedCount = cmd.ExecuteNonQuery(); }
catch (Exception expe)
{ MessageBox.Show(expe.Message); connect.Close(); }
}
else
{
MessageBox.Show("Connection Failed");
}
}
OleDbDataAdapter da = new OleDbDataAdapter();
da.SelectCommand = new OleDbCommand("SELECT * FROM ReceiptItem", connect);
DataTable dt = new DataTable();
da.Fill(dt);
textBoxCurrentCartSumTXT.Clear();
textBoxPricePerOneTXT.Clear();
textBoxQuantityTXT.Clear();
textBoxSumForCurrentItemTXT.Clear();
connect.Close();
}
Items
ItemId
Item Name
Item Price
Recipet
ReciptID
ReciptInvoiceNo
ReciptDateTime
ReciptItem
ReciptID
ItemID
Quantity
UnitPrice

Categories

Resources