asp.net postgresql connection CRUD - c#

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

Related

How to do Automatic synchronize between database access and DatagridView in c#

in my program when i delete a record, it deleted from database access and from the DataGridView , but when i close the window and open it again the record appear again in DataGridView ,Although it deleted from database access ,Here is my code :
private void button1_Click(object sender, EventArgs e)
{
connection.Open();
command.Connection = connection;
string query = " delete from Hoteldb where ID= " +textBox0.Text + "";
MessageBox.Show(query);
command.CommandText = query;
command.ExecuteNonQuery();
MessageBox.Show("Guest Checked Out succesfly");
BindGridView();
}
public void BindGridView()
{
string strSQL = "SELECT * FROM Hoteldb";
OleDbCommand cmd = new OleDbCommand(strSQL, connection);
DataTable table = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(table);
dataGridView1.DataSource = table;
connection.Close();
}
Try this :
private void button1_Click(object sender, EventArgs e)
{
int RowsAffected = 0;
connection.Open();
string query = "DELETE FROM Hoteldb WHERE ID=#ID";
command = new OleDBCommand(query);
command.Connection = connection;
cmd.Parameters.Add(new OleDbParameter("#ID", OleDbType.WChar, 150, "ID"));
cmd.Parameters["#ID"].Value = textBox0.Text.Trim()
RowsAffected = command.ExecuteNonQuery();
if(RowsAffected > 0)
{
MessageBox.Show("Guest Checked Out succesfly");
BindGridView();
}
else
{
MessageBox.Show("There was nothing to be deleted");
}
}
public void BindGridView()
{
connection.Open();
string strSQL = "SELECT * FROM Hoteldb";
cmd = new OleDbCommand(strSQL);
cmd.Connection = connection;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "Hoteldb");
dataGridView1.DataSource = ds.Tables["Hoteldb"].DefaultView
connection.Close();
}

Error/exception handling (try-catch) C#

How to achieve the requirements below:
The Retrieve button click event:
if user doesn't enter CustID in txtCustID need to inform them to enter Customer Id via lblMessage;
if entered CustId doesn't exist in database inform user that it doesn't exist via lblMessage.
The Update button click event - need to ensure that Customer ID already exists in the database.
The Delete button click event: same requirements as for Retrieve button.
I must use error/exception handling (try-catch) to achieve these (project requirement). I spent hours trying, but no success. I would be very grateful for some help! My code is below:
namespace ACME
{
public partial class Customer : System.Web.UI.Page
{
SqlConnection conn;
SqlDataAdapter adapter = new SqlDataAdapter();
DataTable table = new DataTable();
SqlCommand command = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
{
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
}
private void Page_PreInit(object sender, EventArgs e)
{
HttpCookie setTheme = Request.Cookies.Get("UserSelectedTheme");
if (setTheme != null)
{
Page.Theme = setTheme.Value;
}
}
protected void Clear()
{
txtCustID.Text = "";
txtFirstname.Text = "";
txtSurname.Text = "";
rbtGender.SelectedValue = "";
txtAge.Text = "";
txtAddress1.Text = "";
txtAddress2.Text = "";
txtCity.Text = "";
txtPhone.Text = "";
txtMobile.Text = "";
txtEmail.Text = "";
txtEmail2.Text = "";
}
protected void btnNew_Click(object sender, EventArgs e)
{
SqlDataAdapter adapter1 = new SqlDataAdapter();
DataTable table1 = new DataTable();
SqlCommand command1 = new SqlCommand();
Clear();
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
command1.Connection = conn;
command1.CommandType = CommandType.StoredProcedure;
command1.CommandText = "LargestCustID";
command1.Connection.Open();
int id = (int)command1.ExecuteScalar() + 1;
txtCustID.Text = id.ToString();
command1.Dispose();
conn.Close();
}
protected void btnAdd_Click(object sender, EventArgs e)
{
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "AddCustomer";
command.Connection.Open();
command.Parameters.AddWithValue("#CustID",
int.Parse(txtCustID.Text));
command.Parameters.AddWithValue("#Firstname", txtFirstname.Text);
command.Parameters.AddWithValue("#Surname", txtSurname.Text);
command.Parameters.AddWithValue("#Gender", rbtGender.SelectedValue);
command.Parameters.AddWithValue("#Age", int.Parse(txtAge.Text));
command.Parameters.AddWithValue("#Address1", txtAddress1.Text);
command.Parameters.AddWithValue("#Address2", txtAddress2.Text);
command.Parameters.AddWithValue("#City", txtCity.Text);
command.Parameters.AddWithValue("#Phone", txtPhone.Text);
command.Parameters.AddWithValue("#Mobile", txtMobile.Text);
command.Parameters.AddWithValue("#Email", txtEmail.Text);
adapter.InsertCommand = command;
adapter.InsertCommand.ExecuteNonQuery();
lblMessage.Text = "The new record has been added to the database!";
command.Connection.Close();
Clear();
}
protected void btnRetrieve_Click(object sender, EventArgs e)
{
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "GetCustID";
command.Connection.Open();
SqlParameter param = new SqlParameter();
param.ParameterName = "#CustID";
param.SqlDbType = SqlDbType.Int;
param.Direction = ParameterDirection.Input;
param.Value = int.Parse(txtCustID.Text);
command.Parameters.Add(param);
adapter.SelectCommand = command;
adapter.Fill(table);
int id = table.Rows.Count;
if (id == 0)
{
lblMessage.Text = "Customer ID does not exists!";
}
else
{
lblMessage.Text = "";
txtFirstname.Text = table.Rows[0].Field<string>("Firstname");
txtFirstname.DataBind();
txtSurname.Text = table.Rows[0].Field<string>("Surname");
txtSurname.DataBind();
txtAge.Text = table.Rows[0].Field<int>("Age").ToString();
txtAge.DataBind();
txtAddress1.Text = table.Rows[0].Field<string>("Address1");
txtAddress1.DataBind();
txtAddress2.Text = table.Rows[0].Field<string>("Address2");
txtAddress2.DataBind();
txtCity.Text = table.Rows[0].Field<string>("City");
txtCity.DataBind();
txtPhone.Text = table.Rows[0].Field<string>("Phone");
txtPhone.DataBind();
txtMobile.Text = table.Rows[0].Field<string>("Mobile");
txtMobile.DataBind();
txtEmail.Text = table.Rows[0].Field<string>("Email");
txtEmail.DataBind();
}
command.Connection.Close();
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "UpdateCustomer";
command.Connection.Open();
command.Parameters.AddWithValue("#CustID",
int.Parse(txtCustID.Text));
command.Parameters.AddWithValue("#Firstname", txtFirstname.Text);
command.Parameters.AddWithValue("#Surname", txtSurname.Text);
command.Parameters.AddWithValue("#Gender", rbtGender.SelectedValue);
command.Parameters.AddWithValue("#Age", int.Parse(txtAge.Text));
command.Parameters.AddWithValue("#Address1", txtAddress1.Text);
command.Parameters.AddWithValue("#Address2", txtAddress2.Text);
command.Parameters.AddWithValue("#City", txtCity.Text);
command.Parameters.AddWithValue("#Phone", txtPhone.Text);
command.Parameters.AddWithValue("#Mobile", txtMobile.Text);
command.Parameters.AddWithValue("#Email", txtEmail.Text);
lblMessage.Text = "The record has been updated!";
command.Connection.Close();
Clear();
}
protected void btnDelete_Click(object sender, EventArgs e)
{
try
{
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "DeleteCustomer";
command.Connection.Open();
SqlParameter param = new SqlParameter();
param.ParameterName = "#CustID";
param.SqlDbType = SqlDbType.Int;
param.Direction = ParameterDirection.Input;
param.Value = int.Parse(txtCustID.Text);
command.Parameters.Add(param);
adapter.DeleteCommand = command;
adapter.DeleteCommand.ExecuteNonQuery();
int id = (int)param.Value;
command.Connection.Close();
}
catch (Exception ex)
{
lblMessage.Text += "Please enter Customer ID!";
}
try
{
lblMessage.Text = "";
SqlParameter param = new SqlParameter();
param.ParameterName = "#CustID";
param.SqlDbType = SqlDbType.Int;
param.Direction = ParameterDirection.Input;
param.Value = int.Parse(txtCustID.Text);
command.Parameters.Add(param);
adapter.DeleteCommand = command;
adapter.DeleteCommand.ExecuteNonQuery();
int id = table.Rows.Count;
id = (int)param.Value;
lblMessage.Text += "Customer record has been deleted";
command.Connection.Close();
}
catch (Exception ex)
{
lblMessage.Text = "Customer ID doesnot exists!";
}
Clear();
}
public string CustID { get; set; }
}
}
It sounds like you are trying to control flow of your application by use of exceptions. There are many reasons against this approach:
1) Code is difficult to understand and to debug.
2) Throwing exceptions in .Net is expensive.
3) If exception control flow of application how do you differentiate them from a real exceptions (thrown when something doesn't work as expected)?
If, on the other hand, you want to throw an exception when any of the scenarios you listed in the question happens then you can use standard .Net Exception class:
if (string.IsNullOrWhiteSpace(txtCustID.Text))
{
throw new Exception("Id not provided.");
}
Or you can create a custom exception to provide some more specific information:
public class IdNotProvidedException : Exception
{
public string MyCommandName { get; set; }
public IdNotProvidedException(string msg)
: base(msg)
{
}
public IdNotProvidedException(string msg, string myCommandName)
: base(msg)
{
this.MyCommandName = myCommandName;
}
}
And then you initialize and throw your custom exception.
Lastly, there are already places in your code, though not mentioned in your question, that are worth wrapping in a try...catch block. Basically, any place where you connect with the server may result in something unexpected (for instance, the server may not be available).

Search engine by Drop Down List selection and text box entry searches Database for the entry and displays in aspx

I am trying to create a search from ProductDB(database), the main columns I would like the user to search is Material_No and Product_Line.
So far, I have the following:
Drop Down List:
<asp:DropDownList ID="DropDownList" runat="server" Height="16px"
onclick="SearchButton_Click" Width="144px"
AutoPostBack="True">
<asp:ListItem>Please select...</asp:ListItem>
<asp:ListItem Value="0">Material No</asp:ListItem>
<asp:ListItem Value="1">Product Line</asp:ListItem>
</asp:DropDownList>
TextBox:
<asp:TextBox ID="TextBox1" runat="server" ontextchanged="TextBox1_TextChanged">
</asp:TextBox>
Search Button:
<asp:Button ID="SearchButton" runat="server" Text="Search"
onclick="SearchButton_Click" />
So I am trying to do is when the user chooses either Material No or Product Line when he types the Material No or Product Line after clicking the search button, the result should show either in grid format or something similar, and if he just clicks search without choosing anything all the result should show.
Here is what I have done so far.
Old Code:
protected void SearchButton_Click(object sender, EventArgs e)
{
string Selectedvalue = DropDownList.SelectedItem.Value;
if (DropDownList.SelectedItem.ToString() == "Material No")
{
MessageBox.Show("Material No selected");
string textbox = TextBox1.Text;
MessageBox.Show(textbox.ToString());
SqlConnection conn = new SqlConnection("Data Source=localhost;Initial Catalog=ROG;Integrated Security=True");
DataSet dsData = new DataSet();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT * FROM ProductDB WHERE Material_No ='" + TextBox1.Text + "'";
cmd.Connection = conn;
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("", conn);
SqlCommandBuilder cmdBldr = new SqlCommandBuilder(da);
da.Fill(dsData, TextBox1.Text);
MessageBox.Show("Connection Successful");
conn.Close();
}
else
{
MessageBox.Show("Product Line selected");
}
}
New Code:
private SqlConnection conn;
private SqlDataAdapter daMaterial;
private SqlDataAdapter daProduct;
private SqlCommand cmdMaterial;
private SqlCommand cmdProduct;
private SqlParameter paramMaterial;
private SqlParameter paramProduct;
private DataSet dsMaterial;
private DataSet dsProduct;
private DataGrid dgMaterial;
private DataGrid dgProduct;
private const string tableNameMaterial = "Material_No";
private const string tableNameProduct = "Product_Line";
enter code here
protected void SearchButton_Click(object sender, EventArgs e)
{
string Selectedvalue = DropDownList.SelectedItem.Value;
if (DropDownList.SelectedItem.ToString() == "Material No")
{
//MessageBox.Show("Material No. Selected");
string textbox = TextBox1.Text;
//MessageBox.Show(textbox.ToString());
conn = new SqlConnection("Data Source=localhost;Initial Catalog=ROG;Integrated Security=True");
dsMaterial = new DataSet();
daMaterial = new SqlDataAdapter("SELECT * FROM ProductDB WHERE Material_No = #Material_No", conn);
daMaterial.SelectCommand.CommandText = "SELECT * FROM ProductDB WHERE Material_No = #Material_No";
paramMaterial = new SqlParameter();
paramMaterial.ParameterName = "#Material_No";
paramMaterial.Value = TextBox1.Text;
daMaterial.SelectCommand = cmdMaterial;
cmdMaterial.Parameters.Add("#Material_No", SqlDbType.BigInt).Value = TextBox1.Text;
daMaterial.Fill(dsMaterial, tableNameMaterial);
//MessageBox.Show("Connection Successful");
conn.Close();
}
else
{
//MessageBox.Show("Product Line selected");
string textbox = TextBox1.Text;
//MessageBox.Show(textbox.ToString());
conn = new SqlConnection("Data Source=localhost;Initial Catalog=ROG;Integrated Security=True");
dsProduct = new DataSet();
daProduct = new SqlDataAdapter("SELECT * FROM ProductDB WHERE Product_Line = #Product_Line", conn);
daProduct.SelectCommand.CommandText = "SELECT * FROM ProductDB WHERE Product_Line = #Product_Line";
paramProduct = new SqlParameter();
paramProduct.ParameterName = "#Product_Line";
paramProduct.Value = TextBox1.Text;
daProduct.SelectCommand = cmdProduct;
cmdProduct.Parameters.Add("#Product_Line", SqlDbType.VarChar, 50).Value = TextBox1.Text;
conn.Open();
daProduct.Fill(dsProduct, tableNameProduct);
//MessageBox.Show("Connection Successful");
conn.Close();
}
}
I am getting an error "Object reference not set to an instance of an object."
Can someone check whether the Parameter use is correct with the SqlDataAdapter
protected void btnSearch_Click(object sender, EventArgs e)
{
string Query = string.Empty;
try
{
if (sqlCon.State == ConnectionState.Closed)
{
sqlCon.Open();
}
if (DropDownList1.SelectedValue.ToString() == "Name")
{
Query = "select * from tbl_Employee where Name Like '" + txtSearchName.Text + "%'";
}
else if (DropDownList1.SelectedValue.ToString() == "Designation")
{
Query = "select * from tbl_Employee where Designation Like '" + txtSearchName.Text + "%'";
}
SqlDataAdapter sqlDa = new SqlDataAdapter(Query, sqlCon);
DataSet Ds = new DataSet();
sqlDa.Fill(Ds);
dgvEmployee.DataSource = Ds;
dgvEmployee.DataBind();
}
catch (Exception ex)
{
HttpContext.Current.Response.Write("<script>alert('wfrmGrid: 11')</script>" + ex.Message);
}
}
Some things:
daProduct = new SqlDataAdapter("SELECT * FROM ProductDB WHERE Product_Line = #Product_Line", conn);
Creates a new SqlDataAdapter and initializes it's SelectCommand with the CommandText and Connection, hence following lines are redundant and inherently error-prone:
daProduct.SelectCommand.CommandText = "SELECT * FROM ProductDB WHERE Product_Line = #Product_Line";
daProduct.SelectCommand = cmdProduct;
The second instruction even overrides the first with a new CommandText and Connection without ever having used.
paramProduct = new SqlParameter();
Instead of using this parameterless constructor i would use AddWithValue or Parameters.Add which are less error-prone(e.g. you haven't provide a type).
cmdProduct.Parameters.Add( ....
Now you are using the method i've suggested without ever having used paramProduct.
You're also never disposing unmanaged resources(e.g. connections are staying open in case of errors), use the using-statement therefore. Btw, if you use a DataAdapter you don't even need to open/close the connection, that is done implicitely on DataAdapter.Fill.
Sorry, but your code is a mess.Instead of fiddling around with yours, i'll provide a clean version that should work.
....
else
{
using(var con = new SqlConnection("Data Source=localhost;Initial Catalog=ROG;Integrated Security=True"))
using (var daProduct = new SqlDataAdapter("SELECT * FROM ProductDB WHERE Product_Line = #Product_Line", con))
{
daProduct.SelectCommand.Parameters.Add("#Product_Line", SqlDbType.VarChar, 50).Value = TextBox1.Text;
dsProduct = new DataSet();
daProduct.Fill(dsProduct, "Product_Line");
}
}
The following code is working:
private const string tableNameMaterial = "Material_No";
private const string tableNameProduct = "Product_Line";
protected void SearchButton_Click(object sender, EventArgs e)
{
string Selectedvalue = DropDownList.SelectedItem.Value;
if (DropDownList.SelectedItem.ToString() == "Material No")
{
//MessageBox.Show("Material No. Selected");
string textbox = TextBox1.Text;
//MessageBox.Show(textbox.ToString());
SqlConnection conn = new SqlConnection("Data Source=localhost;Initial Catalog=ROG;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM ProductDB WHERE Material_No = #Material_No";
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#Material_No", SqlDbType.BigInt);
cmd.Parameters["#Material_No"].Value = TextBox1.Text;
SqlDataAdapter daMaterial = new SqlDataAdapter();
daMaterial.SelectCommand = cmd;
DataSet dsMaterial = new DataSet();
conn.Open();
daMaterial.Fill(dsMaterial, tableNameMaterial);
//MessageBox.Show("Connection Successful");
GridView1.DataSource = dsMaterial;
GridView1.DataBind();
conn.Close();
}
else
{
//MessageBox.Show("Product Line selected");
string textbox = TextBox1.Text;
//MessageBox.Show(textbox.ToString());
SqlConnection conn = new SqlConnection("Data Source=localhost;Initial Catalog=ROG;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM ProductDB WHERE Product_Line = #Product_Line";
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#Product_Line", SqlDbType.VarChar);
cmd.Parameters["#Product_Line"].Value = TextBox1.Text;
SqlDataAdapter daProduct = new SqlDataAdapter();
daProduct.SelectCommand = cmd;
DataSet dsProduct = new DataSet();
conn.Open();
daProduct.Fill(dsProduct, tableNameProduct);
//MessageBox.Show("Connection Successful");
GridView1.DataSource = dsProduct;
GridView1.DataBind();
conn.Close();
}
}
Now, I need the search box to autocomplete the letters from the database... if anyone has any suggestion, please do share it.
Thank you

dataadapter fill missing parameter

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

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.

Categories