I have a class which I have written all my methods there.
then I have my firstpage of web application which I have some codes there.
I face this
$exception {"Fill: SelectCommand.Connection property has not been initialized."} System.Exception {System.InvalidOperationException}
in the line :
sda.Fill(dsUsers.tblMembers);
here is my code so I hope u can help me:
namespace MosquesNetwork
{
public class cUsers2
{
SqlConnection scn;
SqlDataAdapter sda;
SqlCommandBuilder scb;
SqlCommand SqlStr;
public cUsers2()
{
SqlConnection scn = new SqlConnection (ConfigurationManager.ConnectionStrings["MosquesDBConnectionString"].ConnectionString);
sda = new SqlDataAdapter();
scb = new SqlCommandBuilder(sda);
}
public bool CheckUserName(string UserName)
{
DsUsers2 dsUsers=new DsUsers2();
bool Success;
string SqlStr="select * from tblUsers where Username='"+UserName+"' ";
sda.SelectCommand=new SqlCommand(SqlStr, scn);
sda.Fill(dsUsers.tblMembers);
sda.Fill(dsUsers.tblMembers);
Success=dsUsers.tblMembers.Rows.Count>0;
return Success;
}
then I have this code while the login button is pressed in webform:
protected void Button1_Click(object sender, EventArgs e)
{
if (txtuser.Text.Trim().Length>0 && txtpass.Value.Length>0 )
{
cUsers2 cUsers=new cUsers2();
DsUsers2 dsUser=new DsUsers2();
bool Success;
if (txtuser.Text.Trim()=="admin")
{
Success=cUsers.CheckAdminPass(txtuser.Text.Trim(),txtpass.Value.Trim());
if (Success)
{
Response.Redirect("WebForm2.aspx");
}
}
dsUser=cUsers.Checkpassword(txtuser.Text.Trim(), txtpass.Value.Trim(),out Success);
if(Success)
{
Session["ID"]=dsUser.tblMembers.Rows[0][dsUser.tblMembers.IDUserColumn].ToString();
System.Web.HttpContext.Current.Response.Redirect("frmProfile.aspx");
}
else lblerror.Text="invalid username & password";
}
}
Look at your constructor:
SqlConnection scn = new SqlConnection(...);
That's declaring a separate scn local variable, so the scn instance variable is staying as null. If you just change it to:
scn = new SqlConnection(...);
that may well fix the immediate problem. It's not a nice design in my view - I'd prefer to create the SqlConnection in a using block where you actually need it - but that's what's going wrong for now...
I got also this problem. after search the problem found that the object of connection that i have provide SqlDataAdapter is not Initialize so the connection passed as null
Vishal Sir, If You are Getting that Problem then Be sure whether you are passing the 'cmd' to the SQL DATA ADAPTER.
for eg:
ad = new SqlDataAdapter(cmd);
//Try To Fetch The Value Like this...
protected void Search_Emp_Click(object sender, EventArgs e)
{
SqlCommand cmd;
SqlConnection con;
SqlDataAdapter ad;
con = new SqlConnection(); //making instance of SqlConnection
con.ConnectionString = ConfigurationManager.ConnectionStrings["cn"].ConnectionString; //Invoking Connection String
con.Open(); //Opening Connection
if (Ddl_Emp_Search.SelectedItem.Text == "Date Of Joining")
{
cmd = new SqlCommand("Select Emp_Name,Contact_No,City,Emp_Desig,Place_Code from emp_registration where Emp_Doj=#Emp_Doj",con);
cmd.Parameters.Add("#Emp_Doj", SqlDbType.NVarChar, 50).Value = TextBox1.Text;
}
else if (Ddl_Emp_Search.SelectedItem.Text == "Name")
{
cmd = new SqlCommand("Select Emp_Name,Place_Code,Emp_Code,Emp_Desig from emp_registration where Emp_Name=#Emp_Name", con);
cmd.Parameters.Add("#Emp_Name", SqlDbType.NVarChar, 50).Value = TextBox1.Text;
}
else if (Ddl_Emp_Search.SelectedItem.Text == "Employee Code")
{
cmd = new SqlCommand("Select Emp_Name,Contact_No,City,Emp_Desig,Place_Code from emp_registration where Emp_Code=#Emp_Code", con);
cmd.Parameters.Add("#Emp_Code", SqlDbType.NVarChar, 50).Value = TextBox1.Text;
}
else if (Ddl_Emp_Search.SelectedItem.Text == "City")
{
cmd = new SqlCommand("Select Emp_Name,Contact_No,City,Emp_Desig,Place_Code from emp_registration where City=#City", con);
cmd.Parameters.Add("#City", SqlDbType.NVarChar, 50).Value = TextBox1.Text;
}
else
{
Response.Write("There is Something Worng....");
}
ad = new SqlDataAdapter(cmd); // Here IS THE PROBLEM WHEN YOU DOES'NT PASS CMD (Command instance) to the Data Adapter then there is a problem of ( Fill: SelectCommand.Connection property has not been initialized)
DataSet ds = new DataSet();
ad.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
Related
I am trying to run a SQL query based on who's logged in which gets the Team_ID and assigns it to the session variable. I am having trouble assigning the result to the variable.
protected void ButtonLogin_Click(object sender, EventArgs e)
{
//check what user category was selected and login to appropriate page
if (DropDownListUserType.SelectedIndex == 1)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Web_FussConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from Team_User where Email = #username and Password_1 = #password", con);
cmd.Parameters.AddWithValue("#username", UserName.Text);
cmd.Parameters.AddWithValue("#password", Password.Text);
SqlCommand cmdID = new SqlCommand("select Team_ID from Team_User where Email = #username and Password_1 = #password", con);
cmdID.Parameters.AddWithValue("#username", UserName.Text);
cmdID.Parameters.AddWithValue("#password", Password.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
SqlDataReader reader = cmdID.ExecuteReader();
int Team_ID = reader.GetInt32(1);
Session["Team_ID"] = Team_ID;
Response.Redirect("AddPlayer.aspx");
}
else
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Invalid Username and Password')</script>");
}
}
}
Your code doesn't make a whole lot of sense....
If you only want the Team_ID - why are you loading the whole row first, and then call the database again to get just the Team_ID???
I tried to simplify your code a good bit:
protected void ButtonLogin_Click(object sender, EventArgs e)
{
// check what user category was selected and login to appropriate page
if (DropDownListUserType.SelectedIndex == 1)
{
// define connection string and SQL query as strings
string connectionString = ConfigurationManager.ConnectionStrings["Web_FussConnectionString"].ConnectionString;
string query = "SELECT Team_ID FROM dbo.Team_User WHERE Email = #username AND Password_1 = #password";
// set up SqlConnection and SqlCommand in "using" blocks
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query, con))
{
// define and fill parameters - DO NOT use .AddWithValue!
cmd.Parameters.Add("#username", SqlDbType.VarChar, 100).Value = UserName.Text;
cmd.Parameters.Add("#password", SqlDbType.VarChar, 100).Value = Password.Text;
// open connection, execute scalar, close connection
con.Open();
object result = cmd.ExecuteScalar();
// if we got back a result ....
if(result != null)
{
int teamID = Convert.ToInt32(result.ToString());
Session["Team_ID"] = teamID;
Response.Redirect("AddPlayer.aspx");
}
else
{
// if result is NULL, then the username+password
// were NOT found - do what needs to be done in that case here
}
}
}
}
I have created a web page in Asp.net website. The following page load will run as it gets arguments from previous page. The page also has an option for editing the contents and updating in database. But when the button(save) is clicked it doesn't update the database.Kindly help in this. But when there is no connection in page load the update command works.
protected void Page_Load(object sender, EventArgs e)
{
String cust=Request.QueryString["custName"];
String env = Request.QueryString["env"];
SqlConnection cnn = new SqlConnection();
string connStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
SqlDataAdapter adapter = new SqlDataAdapter();
cnn.ConnectionString = connStr;
cnn.Open();
view();
if (env == "Production")
{
DataSet MyDataSet = new DataSet();
adapter = new SqlDataAdapter("Select * from Customer_Production where Customer_Name=#cust", cnn);
SqlCommandBuilder m_cbCommandBuilder = new SqlCommandBuilder(adapter);
cnn.Close();
//SqlCommand cmd = new SqlCommand("Select * from Customer_Production where Customer_Name=#cust", cnn);
adapter.SelectCommand.Parameters.AddWithValue("#cust", cust);
adapter.Fill(MyDataSet, "Servers");
foreach (DataRow myRow in MyDataSet.Tables[0].Rows)
{
custName.Value = myRow["Customer_name"].ToString();
custMaintain.Value= myRow["Customer_Maintenance"].ToString();
serviceAffect.Value=myRow["Systems/Services_Affected"].ToString();
email_Content.Value= myRow["Email_Content"].ToString();
email_Signature.Value= myRow["Email_Signature"].ToString();
email_From.Value=myRow["Email_From"].ToString();
email_To.Value=myRow["Email_To"].ToString();
email_Cc.Value=myRow["Email_Cc"].ToString();
email_Bcc.Value=myRow["Email_Bcc"].ToString();
}
}
else
{
DataSet MyDataSet = new DataSet();
adapter = new SqlDataAdapter("Select * from Customer_Non_Production where Customer_Name=#cust", cnn);
SqlCommandBuilder m_cbCommandBuilder = new SqlCommandBuilder(adapter);
cnn.Close();
//SqlCommand cmd = new SqlCommand("Select * from Customer_Production where Customer_Name=#cust", cnn);
adapter.SelectCommand.Parameters.AddWithValue("#cust", cust);
adapter.Fill(MyDataSet, "Servers");
foreach (DataRow myRow in MyDataSet.Tables[0].Rows)
{
custName.Value = myRow["Customer_name"].ToString();
custMaintain.Value = myRow["Customer_Maintenance"].ToString();
serviceAffect.Value = myRow["Systems/Services_Affected"].ToString();
email_Content.Value = myRow["Email_Content"].ToString();
email_Signature.Value = myRow["Email_Signature"].ToString();
email_From.Value = myRow["Email_From"].ToString();
email_To.Value = myRow["Email_To"].ToString();
email_Cc.Value = myRow["Email_Cc"].ToString();
email_Bcc.Value = myRow["Email_Bcc"].ToString();
}
}
The following is the button click for Save Button(for update command)
protected void save_click(object sender, EventArgs e)
{
//Button Click Save
/* String id = "A";
SqlConnection cnn = new SqlConnection();
string connStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
SqlDataAdapter adapter = new SqlDataAdapter();
cnn.ConnectionString = connStr;
cnn.Open();
String sql = String.Format("Update Customer_Production set Email_Signature='{0}' where Customer_Name like '{1}'",TextBox1.Text,id);
SqlCommand cmd = new SqlCommand(sql, cnn);
cmd.ExecuteNonQuery();
*/
String cust = "A";
SqlConnection cnn = new SqlConnection();
string connStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
SqlDataAdapter adapter = new SqlDataAdapter();
cnn.ConnectionString = connStr;
cnn.Open();
if (env.Value == "Production")
{
//String sql = String.Format("Update Customer_Production set Customer_Maintenance='{0}',Environment='{1}',[Systems/Services_Affected]='{2}',Email_Content='{3}',Email_Signature='{4}',Email_To='{5}',Email_Cc='{6}',Email_Bcc='{7}',Email_From='{8}' where Customer_Name like '{9}' ", "custMaintain.Value","env.Value","serviceAffect.Value","email_Content.Value","email_To.Value","email_Cc.Value","email_Bcc.Value","email_From.Value", "cust");
String sql = String.Format("Update Customer_Production set Email_Signature='{0}' where Customer_Name like '{1}'", email_Signature.Value,cust);
SqlCommand cmd = new SqlCommand(sql, cnn);
cmd.ExecuteNonQuery();
}
else
{
}
}
I'm not sure why having a connection (or not) in the Page_Load would make a difference, but here's one thing that looks off to me:
String.Format(
"Update Customer_Production set Email_Signature='{0}' where Customer_Name like '{1}'",
email_Signature.Value,
cust);
(I broke it into several lines because the part I'm interested in is the last part of the format string.)
You've set cust to "A" earlier in that method. So the SQL that will result will look (at the end) like this:
... where Customer_Name like 'A'
Unless you have a customer name that is exactly equal to A, that's not going to return anything, and therefore no records will be updated. You're forgetting the '%' wildcard.
I agree with all those who have pointed out that your code is vulnerable to SQL injection (and you'll also have a problem with single quotes), but just to show you what it needs to look like, here it is with the wildcard:
Update Customer_Production set Email_Signature='{0}' where Customer_Name like '{1}%'
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
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();
}
}
}'
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.