dataadapter fill missing parameter - c#

I recieve the following error when I try to execute this code. But I added it to my commands. Can someone point out the step that overlooked? Thanks.
Procedure or function 'usps_getContactDetails' expects parameter '#aspContactID', which was not supplied.
SqlConnection conn = new SqlConnection(GetConnString());
SqlCommand cmd = new SqlCommand("usps_getContactDetails", conn);
SqlParameter parmContactID = new SqlParameter("#aspContactID", Convert.DBNull);
cmd.Parameters.Add(parmContactID);
parmContactID.Direction = ParameterDirection.Input;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
conn.Open();
DataSet cusDS = new DataSet();
da.Fill(cusDS, "Contacts");

When doing a SqlCommand and calling a stored procedure, you need to implicity set your SqlCommand to be a StoredProcedure.
using(SqlConnection con = new SqlConnection(""))
{
//Set up your command
SqlCommand cmd = new SqlCommand("[Procedure]", con);
cmd.CommandType = CommandType.StoredProcedure;
//Add your parameters
cmd.Parameters.AddWithValue("#aspContactID", "");
//Declare your data adapter
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds, "Contacts");
}
Follow the above format and you should be fine. Your procedure isn't working for one of two reasons, you were missing the line of code which makes your code work in this case is cmd.CommandType = CommandType.StoredProcedure; or because your parameter is DBNull the procedure says it doesn't have any recognition of that parameter. If you have a parameter which can be null or empty in a stored procedure then do the following:
Create Procedure [dbo].[Example]
#Test as Varchar(100) = ''
As

protected void Page_Load(object sender, EventArgs e)
{
}
private void OpenCon()
{
con = new SqlConnection(ConfigurationManager.ConnectionStrings["DbPrepConnectionString"].ConnectionString.ToString());
try
{
con.Open();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
private void SubmitData()
{
OpenCon();
string sp = "sp_InsertRecord";
cmd = new SqlCommand(sp, con);
cmd.CommandType = CommandType.StoredProcedure;
//add parameters...
cmd.Parameters.Add(new SqlParameter("#Name", SqlDbType.VarChar, 50));
cmd.Parameters.Add(new SqlParameter("#UserId", SqlDbType.Int));
cmd.Parameters.Add (new SqlParameter ("#ProductName",SqlDbType .VarChar,50));
cmd.Parameters.Add(new SqlParameter("#Price", SqlDbType.Money));
//set paarameters....
cmd.Parameters["#Name"].Value = txtName.Text.ToString();
cmd.Parameters["#UserId"].Value = txtUserId.Text.ToString();
cmd.Parameters["#ProductName"].Value = txtProductName.Text.ToString();
cmd.Parameters["#Price"].Value = txtPrice.Text.ToString();
cmd.ExecuteNonQuery();
lblMessage.Text = "data inserted successfully";
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
SubmitData();
}
private void FindData()
{
OpenCon();
string s = "sp_FindRecord";
cmd = new SqlCommand(s, con);
cmd.Parameters.Add(new SqlParameter("#Id", SqlDbType.Int));
cmd.Parameters["#Id"].Value = txtName.Text.ToString();
cmd.CommandType = CommandType.StoredProcedure;
ad = new SqlDataAdapter(cmd);
ds = new DataSet();
ad.Fill(ds);
dt = ds.Tables[0];
currow = 0;
FillControls();
}
private void FillControls()
{
txtOrderId.Text = dt.Rows[currow].ItemArray[0].ToString();
txtUserId.Text = dt.Rows[currow].ItemArray[1].ToString();
txtProductName.Text = dt.Rows[currow].ItemArray[2].ToString();
txtPrice.Text = dt.Rows[currow].ItemArray[3].ToString();
}
protected void btnFind_Click(object sender, EventArgs e)
{
FindData();
}
}
}'

Related

asp.net postgresql connection CRUD

I have a problem with data management in the postgre database. I`m connected, now i want to add any value, but that what i wrote dosent work.
protected void Page_Load(object sender, EventArgs e)
{
try
{
Label1.Text = "Połączenie z bazą danych zakonczońe sukcesem";
NpgsqlConnection conn = new NpgsqlConnection("Server=localhost;Port=5432;Database=dt_PackageWarehouse;User Id=postgres;Password=321qweQAZ");
conn.Open();
NpgsqlCommand comm = new NpgsqlCommand();
comm.Connection = conn;
comm.CommandType = CommandType.Text;
comm.CommandText = "select * from magazynpaczek";
NpgsqlDataAdapter nda = new NpgsqlDataAdapter(comm);
DataTable dt = new DataTable();
nda.Fill(dt);
comm.Dispose();
conn.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception)
{
Label1.Text = "Połączenie z bazą danych zakonczońe niepowodzeniem";
}
}
protected void btnDodaj_Click(object sender, EventArgs e)
{
NpgsqlConnection conn = new NpgsqlConnection("Server=localhost;Port=5432;Database=dt_PackageWarehouse;User Id=postgres;Password=321qweQAZ");
string query = "Insert into public.magazynpaczek(id, nazwafirmynadawcy, imienadawcy, nazwiskonadawcy, nrtelefonunadawcy, miastonadawcy, ulicanadawcy, nazwafirmyodbiorcy," +
" imieodbiorcy, nazwiskoodbiorcy, nrtelefonuodbiorcy, miastoodbiorcy, ulicaodbiorcy, nrprzesylki, datadoreczenia) VALUES(#NFN, #txtIN, #txtNN, #txtNTN, #txtMN," +
"#txtUN, #txtNFO, #txtIO, #txtNO, #txtNTO, #txtMO, #txtUO, #txtNP, #txtDD)";
NpgsqlCommand comm = new NpgsqlCommand(query, conn);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
}
you have to create and add a parameter for each insert value:
var query = "Insert into public.magazynpaczek(id, nazwafirmynadawcy, imienadawcy, nazwiskonadawcy, nrtelefonunadawcy, miastonadawcy, ulicanadawcy, nazwafirmyodbiorcy," +
" imieodbiorcy, nazwiskoodbiorcy, nrtelefonuodbiorcy, miastoodbiorcy, ulicaodbiorcy, nrprzesylki, datadoreczenia) VALUES(#NFN, #txtIN, #txtNN, #txtNTN, #txtMN," +
"#txtUN, #txtNFO, #txtIO, #txtNO, #txtNTO, #txtMO, #txtUO, #txtNP, #txtDD)";
IDbCommand command = conn.CreateCommand();
command.CommandText = query;
var parameter = command.CreateParameter();
parameter.ParameterName = "NFN";
parameter.Value = nfn;
command.Parameters.Add(parameter);
parameter = command.CreateParameter();
parameter.ParameterName = "txtIN";
parameter.Value = txtIN.text;
command.Parameters.Add(parameter);
.... and so on
conn.Open();
command.ExecuteNonQuery();
conn.Close();

Procedure or function 'select1_customer' expects parameter '#Customerid', which was not supplied

This is my code :
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
mytable = new DataTable();
mytable.Columns.Add("Customerid");
mytable.Columns.Add("Customername");
mytable.Columns.Add("Contactname");
mytable.Columns.Add("Address");
mytable.Columns.Add("Mobile");
GridView1.DataSource = mytable;
GridView1.DataBind();
string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
//SqlCommand cmd = new SqlCommand("select * from Table_3", con);
SqlCommand cmd = new SqlCommand("select1_customer", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(mytable);
GridView1.DataSource = mytable;
GridView1.DataBind();
}
}
Procedure or function 'select1_customer' expects parameter '#Customerid', which was not supplied. it was my error
Your are missing
cmd.Parameters.AddWithValue("#Customerid", required value);
Try,
SqlCommand cmd = new SqlCommand("select1_customer", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Customerid", "value_for_CustomerID");
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(mytable);
GridView1.DataSource = mytable;
GridView1.DataBind();

How to populate a DataGridView by selecting any table from combo box

I have used the following code for displaying names of my SQL db tables in a combo box.
Now I want that when I click on any of these table names from the combo box, my DGV populates with that table's contents.
private void Form1_Load(object sender, EventArgs e)
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select table_name from information_schema.tables";
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
comboBox1.DataSource = dtRecord;
comboBox1.DisplayMember = "TABLE_NAME";
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Then I used the following code for populating my DGV but it's not working; please help.
private void PopulateGridView()
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strconnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "select * from " + comboBox1.SelectedText;
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dtRecord;
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedValue != null)
{
PopulateGridView(comboBox1.SelectedValue.ToString());
}
}
just try this:
update your code in the Form Load with below:
private void Form1_Load(object sender, EventArgs e)
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select table_name from information_schema.tables";
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
comboBox1.DataSource = dtRecord;
comboBox1.DisplayMember = "table_name";
comboBox1.ValueMember = "table_name";
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
so basically you have added one extra line comboBox1.ValueMember = "table_name";
and make your PopulateGridView method like this:
private void PopulateGridView(string tblName)
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "select * from " + tblName;
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dtRecord;
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
it has to work.
Also, I see, you are creating SqlConnection object everywhere, including SqlCommand and SqlDataAdapter.
try to wrap them up in static methods i.e.
- public static SqlConnection OpenConnection()
- public static DataTable ExecuteSelectQuery(string Query)
- public static bool ExecuteModifyQuery(string Query)
try to write as less amount of code as you can.
Try this:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedValue != null)
{
string strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strconnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "select * from " + comboBox1.SelectedValue;
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dtRecord;
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}

Search and display in gridview

I've been working on this one since someone teaches me to use gridview to display my search result.
My problem is, I can't even make it work, when I click or hit the search button, nothing happen. I have:
-1 textbox for last name
-2 dropdownlist for the province and city
-and a search(trigger)button
Here's what I've done so far:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_province");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_province ORDER BY PROVINCE_NAME ASC", conn);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
}
ddlProvince.DataSource = dt;
ddlProvince.DataTextField = "PROVINCE_NAME";
ddlProvince.DataValueField = "PROVINCE_CODE";
ddlProvince.DataBind();
}
}
protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
{
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_province");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_city WHERE PROVINCE_CODE =#pcode", conn);
comm.Parameters.AddWithValue("#pcode", ddlProvince.SelectedValue);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
SqlParameter param = new SqlParameter();
param.ParameterName = "#pcode";
param.Value = ddlProvince;
comm.Parameters.Add(param);
}
ddlCity.DataSource = dt;
ddlCity.DataTextField = "CITY_NAME";
ddlCity.DataValueField = "CITY_CODE";
ddlCity.DataBind();
}
private void BindGridView(string field)
{
DataTable dt = new DataTable();
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
try
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_accredited_providers WHERE DOCTOR_CODE =#pcode", conn);
comm.Parameters.AddWithValue("#pcode", ddlProvince.SelectedValue);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
SqlParameter param = new SqlParameter();
param.ParameterName = "#pcode";
param.Value = ddlProvince;
comm.Parameters.Add(param);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
else
{
}
// NO RECORDS FOUND
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
protected void btnSearch_Click(object sender, EventArgs e)
{
BindGridView(txtName.Text.Trim());
}
}
I'm new to this, please assist me. Thanks!
You are not using the field string variable that you are passing to BindGridView and you are mismanaging your SQL parameters (adding the same parameter twice and assigning a DropDown object as a parameter value).
You are adding the same parameter twice.
To fix this, remove this line: comm.Parameters.AddWithValue("#pcode", ddlProvince.SelectedValue);
You are not using the field variable.
To fix this, change this line
param.Value = ddlProvince; // Note: You are assigning a dropdown OBJECT as the value here!
to
param.Value = field;
in your BindGridView function.

Saving ID to database based on dropdown selection

I am using the following code to bind BusinessID as the DataValueField of the ddlIndustry dropdown. What I want to do is save the selected ID to a different table (Company). I am doing this with ddlIndustry.SelectedValue. For some reason, the first value is always saved (1), and not the selected value. Do you have any ideas as to why this might be happening?
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
BindCountry();
BindIndustry();
}
private void BindCountry()
{
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("countries.xml"));
foreach (XmlNode node in doc.SelectNodes("//country"))
{
ddlCountry.Items.Add(new ListItem(node.InnerText, node.Attributes["code"].InnerText));
ddlCountry.SelectedIndex = 94;
}
}
private void BindIndustry()
{
SqlCommand cmd = null;
SqlConnection conn = new SqlConnection(GetConnectionString());
conn.Open();
cmd = new SqlCommand("Select Industry, BusinessID FROM BusinessType", conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
conn.Close();
ddlIndustry.DataSource = ds;
ddlIndustry.DataTextField = "Industry";
ddlIndustry.DataValueField = "BusinessID";
ddlIndustry.DataBind();
//ddlIndustry.Items.Insert(0, new System.Web.UI.WebControls.ListItem("-- Please Select Industry --", "0"));
}
private void ExecuteCompanyDetailsInsert()
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "INSERT INTO Company (BusinessID, CompanyName, Email, AddressLine1, AddressLine2, Location, Telephone) VALUES "
+ " (#BusinessID, #CompanyName, #Email, #AddressLine1, #AddressLine2, #Location, #Telephone)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] param = new SqlParameter[7];
param[0] = new SqlParameter("#BusinessID", SqlDbType.Int);
param[1] = new SqlParameter("#CompanyName", SqlDbType.VarChar, 50);
param[2] = new SqlParameter("#Email", SqlDbType.VarChar, 50);
param[3] = new SqlParameter("#AddressLine1", SqlDbType.VarChar, 50);
param[4] = new SqlParameter("#AddressLine2", SqlDbType.VarChar, 50);
param[5] = new SqlParameter("#Location", SqlDbType.VarChar, 50);
param[6] = new SqlParameter("#Telephone", SqlDbType.VarChar, 50);
param[0].Value = ddlIndustry.SelectedValue;
param[1].Value = company_name.Text;
param[2].Value = company_email.Text;
param[3].Value = address_line_1.Text;
param[4].Value = address_line_2.Text;
param[5].Value = ddlCountry.SelectedItem.Text;
param[6].Value = telephone.Text;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
First of all modify this code, because when your page is postback to server, your industry dropdown bind again and your selected value lost
if (!Page.IsPostBack)
{
BindCountry();
BindIndustry();
}
and then you can get selected value
ddlIndustry.SelectedValue

Categories