getting a single databse value into text box - c#

I would really appreciate if there is any reference to show in how i could transfer value from database into textbox. This my code for combobox, but instead of combobox i would like in textbox
OleDbDataAdapter oda = new OleDbDataAdapter("select subject_name from subjecti where subject_name = '" + comboBoxSubjectName.Text + "'", con);
DataTable dt = new DataTable();
oda.Fill(dt);
comboBoxSubjectCodeUpdate.DataSource = dt;
comboBoxSubjectCodeUpdate.DisplayMember = "subject_name";

You can try something like this
string myquery = "SELECT MyColumn FROM MyTable";
using (var command = new OleDbCommand(myquery, connection))
{
MyTextBox.Text = command.ExecuteScalar().ToString();
}
Please note if you will be returning multiple values then I suggest you use ExecuteReader() as ExecuteScalar() only returns a single value.

Related

How can i get the value of column field base on another column field

Im using Visual Studio C# and using Access as my database. I have two columns, ItemCode and ProductName. I want to auto input of the productname on its textbox whenever its itemcode was selected. how can I do this?
some codes:
try
{
con.Open();
OleDbCommand command = new OleDbCommand(#"Select * from TblInventory where ItemCode='" + txtItem.Text + "'");
command.Connection = con;
command.Parameters.AddWithValue("itemcode", txtItem.Text);
OleDbDataReader reader = command.ExecuteReader();
if (reader.Read())//Update Item Code is already exist
{
.........
Feel free to edit my question and please be kind. thank you guys
Try this .
text_box.Text=reader["ProductName"].ToString();
You are filtering the rows by specifying the ItemCode in the Where clause, So The reader will contains the corresponding row/s that matches the specified code. What you need to do is Access the required column value by specifying the name as like the above snippet.
For extracting data from database, I prefer that use OleDbDataAdapter.
You can simply use:
string command = #"Select * from TblInventory where ItemCode='" + txtItem.Text + "'";
OleDbDataAdapter da = new OleDbDataAdapter(command, con);
DataTable dt = new DataTable();
da.Fill(dt);
Now, use dt :
if (dt.Rows.Count == 0)
//Error Message
else
cmbTreatyTitle.Text = dt.Rows[0]["ProductName"].ToString();
I hope this is helpful.

asp.net - searching for a data containing an apostrophe in the database

Good day! I am having a hard time fixing this problem. I've been searching the answer for this but seemed to be very very hard to look for the most fitting answer.
i use this query to search for a tenant's name based on what the user inputs in the txtSearchRP textbox, it works very well to data with no apostrophe in it, however when the user searches for a name containing ' , it does not function well.
example: user inputs MAX'S to search MAX'S RESTAURANT
SELECT * from tenant WHERE (name LIKE '%" + txtSearchRP.Text + "%')
Thanks for your help in advance!
edit for more information:
I am actually passing the query to sqlDataSource to bind the gridview automatically after the user click THE BUTTON.
SqlDataSource3.SelectCommand = SELECT * from tenant WHERE (name LIKE '%" + txtSearchRP.Text + "%')
Try this
conn = new
SqlConnection("ConnectionString");
conn.Open();
SqlCommand cmd = new SqlCommand(
"SELECT * from tenant WHERE (name LIKE #tenant)", conn);
SqlParameter param = new SqlParameter();
param.ParameterName = "#tenant";
param.Value = "%" + txtSearchRP.Text + "%"; // you can use any wildcard operator
cmd.Parameters.Add(param);
SqlDataReader reader = cmd.ExecuteReader();
In addition to the answers already given, in some applications, you might need to consider escaping wildcards such as % in the input string provided by the user.
For example, if the user enters "25%", then matching on "%25%%" will return values that contain "25", rather than restricting to values that contain "25%".
You can escape wildcards as follows (for SQL Server):
string value = ... value entered by user;
value = value.Replace("[", "[[]");
value = value.Replace("_", "[_]");
value = value.Replace("%", "[%]");
Better way create storedprocedure
SP :
Create proc sp_Search( #txtSearch nvarchar(150))
as begin
SELECT * from tenant WHERE name like #txtSearch+'%'
end
Code behind :
string txtSearch = txtSearchRP.Text;
SqlDataReader dr;
using (SqlConnection conn = new SqlConnection(cn.ConnectionString))
{
using (SqlCommand cmdd = new SqlCommand())
{
cmdd.CommandType = CommandType.StoredProcedure;
cmdd.CommandText = "sp_Search";
cmdd.Parameters.AddWithValue("#txtSearch", txtSearch);
cmdd.Connection = conn;
conn.Open();
dr = cmdd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows)
{
while (dr.Read())
{
var name = dr["name"].ToString();
var location = dr["location"].ToString();
}
} dr.Close();
conn.Close();
}
}
Updated:
Write a function which returns datatable so that we can bind it to our gridview control as i did in code below
public DataTable bindGridView()
{
string txtSearch = txtSearchRP.Text;
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(cn.ConnectionString))
{
SqlCommand cmdd = new SqlCommand();
cmdd.CommandType = CommandType.StoredProcedure;
cmdd.CommandText = "sp_Search";
cmdd.Parameters.AddWithValue("#txtSearch", txtSearch);
cmdd.Connection = con;
con.Open();
SqlDataAdapter dap = new SqlDataAdapter(cmdd);
DataSet ds = new DataSet();
dap.Fill(ds);
dt = ds.Tables[0];
con.Close();
}
return dt;
}
On Button click : Call bindGridView() function for binding Gridview control
GridView1.DataSource = bindGridView();
GridView1.DataBind();
thanks to all who shared their knowledge and effort, finally got the answer through the String replace method
HERE'S THE 3-LINED CODE
string value = txtSearchRP.Text;
value = value.Replace("'", "['']");
sqlDataSource3.SelectCommand = "SELECT * from tenant WHERE (name LIKE '%" + value.ToString() +"%')";
through the joined effort, answers you posted here, we solve the problem in the simplest form :)

Using ExecuteReader instead of SQLDataAdapter

I've got a C# project where I'm trying to export the results of a datagrid. Sometimes the data gets quite large, so rather than re-executing the code I want to dump the dataset into a session variable.
This works perfectly in most of my projects. One example from a project where I use this is:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection sqlconnectionStatus = new SqlConnection(str);
string DDL_Value = Convert.ToString(Request.QueryString["DDL_Val"]);
//Use the ClassTesting class to determine if the dates are real, and fill in today's date if they're blank
string StDt_Value = ClassTesting.checkFields(Request.Form["txtStartDate"], "Date");
string EnDt_Value = ClassTesting.checkFields(Request.Form["txtEndDate"], "Date");
//string StDt_Value = Convert.ToString(Request.QueryString["StDt_Val"]);
//string EnDt_Value = Convert.ToString(Request.QueryString["EnDt_Val"]);
string BTN_Value;
// Because the date is stored as an INT, you have to request the string and then
// convert it to an INT
string StDT_Vals = Request.QueryString["StDt_Val"].ToString();
string EnDT_Vals = Request.QueryString["EnDt_Val"].ToString();
//sqlquery = "Select PROC_NM as 'Agent Name', AdminLevel as Role, Count(Claim_ID) as 'Count of Claims Reviewed', Spare as AgentID ";
//sqlquery = sqlquery + "from ClosedClaims_MERGE CCM ";
sqlquery = "Select PROC_NM as 'Agent Name', AdminLevel as Role, Count(DISTINCT Claim_ID) as 'Count of Claims Reviewed', Spare as AgentID ";
sqlquery = sqlquery + "from (SELECT DISTINCT Spare, SpareFinished, CLAIM_ID FROM ClosedClaims_MERGE ";
sqlquery = sqlquery + "UNION SELECT DISTINCT Spare, SpareFinished, CLAIM_ID FROM tblAuditing) CCM ";
sqlquery = sqlquery + "LEFT JOIN PROC_LIST PL ON CCM.Spare = PL.LOGIN ";
sqlquery = sqlquery + "WHERE CCM.SpareFinished >= '" + StDt_Value + "' AND CCM.SpareFinished <= '" + EnDt_Value + "' ";
sqlquery = sqlquery + "GROUP BY Spare, PROC_NM, AdminLevel ";
sqlquery = sqlquery + "ORDER BY Count(Claim_ID) DESC";
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = new SqlCommand(sqlquery, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// Fill the DataSet.
DataSet ds = new DataSet();
adapter.Fill(ds, "dsEffVol");
// Add this to a session variable so the datagrid won't get NULLed out on repost
Session["SSEffVol"] = ds;
// Perform the binding.
grdEffVol.Attributes.Add("style", "overflow:auto");
//GridView_WODetails.Attributes.Add("style", "table-layout:fixed");
grdEffVol.AutoGenerateColumns = true;
grdEffVol.DataSource = ds;
grdEffVol.DataBind();
}
I've got a new project where I'm not using SQL strings, but instead I'm pulling data based on SQL Server Stored Procedures. The code block there is:
protected void btnSubmit_OnClick(object sender, EventArgs e)
{
List<ReportData> myReportData = new List<ReportData>();
using (SqlConnection connection1 = new SqlConnection(str2))
{
//Query the Reports table to find the record associated with the selected report
using (SqlCommand cmd = new SqlCommand("SELECT * from RM_tblManagerReports WHERE ReportID = " + cboFilterOption.SelectedValue + "", connection1))
{
connection1.Open();
using (SqlDataReader DT1 = cmd.ExecuteReader())
{
while (DT1.Read())
{
//Read the record into an "array", so you can find the SProc and View names
int MyRptID = Convert.ToInt32(DT1[0]);
string MyRptName = DT1[1].ToString();
string MyRptSproc = DT1[2].ToString();
string MySQLView = DT1[3].ToString();
string MyUseDates = DT1[4].ToString();
//Run the Stored Procedure first
SqlConnection connection2 = new SqlConnection(str2);
SqlCommand cmd2 = new SqlCommand();
cmd2.CommandType = CommandType.StoredProcedure;
cmd2.CommandText = "" + MyRptSproc + "";
cmd2.Connection = connection2;
//Set up the parameters, if they exist
if (MyUseDates != "N")
{
cmd2.Parameters.Add("#StDate", SqlDbType.Date).Value = DateTime.Parse(txtStDate.Value);
cmd2.Parameters.Add("#EnDate", SqlDbType.Date).Value = DateTime.Parse(txtEnDate.Value);
}
else
{
}
try
{
connection2.Open();
GridView_Reports.EmptyDataText = "No Records Found";
SqlDataReader dr = cmd2.ExecuteReader(CommandBehavior.CloseConnection);
Session["SSRptMenu"] = dr;
GridView_Reports.DataSource = dr;
GridView_Reports.DataBind();
// Add this to a session variable so the datagrid won't get NULLed out on repost
GridView_Reports.DataBound += GridView_Reports_RowDataBound;
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(btnSubmit, typeof(Button), "Report Menu", "alert('There is no View associated with this report.\\nPlease contact the developers and let them know of this issue.')", true);
Console.WriteLine(ex);
return;
}
finally
{
connection2.Close();
connection2.Dispose();
}
}
}
}
}
}
I'm kind of guessing my way through this, and I'm not sure if I'm reading the data into a dataset properly. The page is shutting down, and I'm pretty sure the problem is in the lines:
SqlDataReader dr = cmd2.ExecuteReader(CommandBehavior.CloseConnection);
Session["SSRptMenu"] = dr;
GridView_Reports.DataSource = dr;
Quite honestly, I've googled SqlDataReader vs SqlDataAdapter and can't really find anything, but I need to fill the session variable in the second example and also have the datagrid populate properly. So, in essence, I need to put the results of a Stored Procedure into a dataset. Can anyone offer suggestions on what I'm doing wrong?
I'm pretty sure most controls don't accept readers in their DataSource property. Plus the majority of readers are forward-only, so although you're trying to store the reader as a session variable, chances are you would only be able to read it once.
Why do you want to use a reader for this when your post seems to indicate that you know you need to use a DataSet? Why not just use an adapter the way you show in your first post? Adapters work fine with commands that use sprocs.
Instead of:
SqlDataReader dr = cmd2.ExecuteReader(CommandBehavior.CloseConnection);
Session["SSRptMenu"] = dr;
GridView_Reports.DataSource = dr;
Just use:
var adapter = new SqlDataAdapter(cmd2);
var ds = new DataSet();
adapter.Fill(ds, "MyTableName");
Session["SSRptMenu"] = ds;
GridView_Reports.DataSource = ds;

c# Using Parameters.AddWithValue in SqlDataAdapter

How can I use Parameters.AddWithValue with an SqlDataAdapter. Below searching codes.
var da = new SqlDataAdapter("SELECT * FROM annotations WHERE annotation LIKE '%"+txtSearch.Text+"%'", _mssqlCon.connection);
var dt = new DataTable();
da.Fill(dt);
I rewrote the code like this:
SqlDataAdapter da;
da = new SqlDataAdapter("SELECT * FROM annotations WHERE annotation LIKE '%#search%'", _mssqlCon.connection);
da.SelectCommand.Parameters.AddWithValue("#search",txtSearch.Text);
var dt = new DataTable();
da.Fill(dt);
but it failed.
The string used to initialize the SqlDataAdapter becomes the CommandText of the SelectCommand property of the SqlDataAdapter.
You could add parameters to that command with this code
da = new SqlDataAdapter("SELECT * FROM annotations WHERE annotation LIKE #search",
_mssqlCon.connection);
da.SelectCommand.Parameters.AddWithValue("#search","%" + txtSearch.Text + "%");
First, remove the single quote around the parameter placeholder.
Second, add the wildcard character directly in the Value parameter of
AddWithValue
You have asked to use AddWithValue, but remember that, while it is a useful shortcut, there are also numerous drawbacks and all well documented.
First: Can we stop using AddWithValue() already? where the
author discuss how AddWithValue could give back wrong results in your
queries
Second: How Data Access Code Affects Database Performance where
the author presents evidences of strong performance problems for
AddWithValue
So, the same code without AddWithValue and using the Object and Collection Initializers syntax could be written as
da = new SqlDataAdapter("SELECT * FROM annotations WHERE annotation LIKE #search",
_mssqlCon.connection);
da.SelectCommand.Parameters.Add(new SqlParameter
{
ParameterName = "#search",
Value = "%" + txtSearch.Text + "%",
SqlDbType = SqlDbType.NVarChar,
Size = 2000 // Assuming a 2000 char size of the field annotation (-1 for MAX)
});
and, an even more simplified and one liner version of the above is:
da.SelectCommand.Parameters.Add("#search",SqlDbType.NVarChar,2000).Value = "%" + txtSearch.Text + "%";
Use da.SelectCommand.Parameters.Add() instead of cmd.Parameters.Add(), here's a sample for dealing with a stored procedure which takes two parameters and second one is a nullable int parameter:
public DataTable GetData(int par1, int? par2)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlDataAdapter da = new SqlDataAdapter())
{
string sql = "StoredProcedure_name";
da.SelectCommand = new SqlCommand(sql, conn);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.Add("#Par1", SqlDbType.Int).Value = par1;
da.SelectCommand.Parameters.Add("#Par2", SqlDbType.Int).Value = (object)par2?? DBNull.Value;
DataSet ds = new DataSet();
da.Fill(ds, "SourceTable_Name");
DataTable dt = ds.Tables["SourceTable_Name"];
//foreach (DataRow row in dt.Rows)
//{
//You can even manipulate your data here
//}
return dt;
}
}
}
Try this:
mySearchString = "Select * From test Where ([title] LIKE '%' + #title + '%')";
cmd.Parameters.Add("#title", SqlDbType.VarChar, 120);
cmd.Parameters("#title").Value = TextBox1.Text;
I use Repeater for show data
int queryString =int.Parse(Request.QueryString["Id"]);
SqlConnection conn =new SqlConnection("server=.; Database=Northwind;
Integrated Security=true;");
try{
conn.Open();
SqlDataAdapter dataAdapter = new SqlDataAdapter("SELECT ProductID, ProductName, UnitPrice, CategoryID FROM Products WHERE CategoryID =#CategoryID", conn);
dataAdapter.SelectCommand.Parameters.Add("#CategoryID", queryString);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
QueryStringProductListRepeater.DataSource = dataSet;
QueryStringProductListRepeater.DataBind();
}
catch{
Response.Write("QueryStringProductListRepeater");
}
finally{
conn.Close();
}

datagrid not getting displayed

I am trying to display the data from sql into a datagrid as follows:
try
{
SqlConnection xconn = new SqlConnection();
xconn.ConnectionString = #"Data Source=servername; Trusted_Connection=yes; Database=master";
xconn.Open();
string s = "select * from tablename where name=#name";
SqlCommand ycmd = new SqlCommand(s, xconn);
ycmd.Parameters.Add("#name", dropdownlistname.SelectedValue);
SqlDataAdapter da = new SqlDataAdapter(ycmd);
DataTable dt = new DataTable();
da.Fill(dt);
gridview.DataSource = dt;
gridview.DataBind();
}
catch (Exception e2)
{
lblresult.Text = e2.Message + "<br />" + e2.StackTrace ;
}
I do not get any exception . However , the grid is not displayed.
try like this....
you can change this depends on your requirement ....
SqlCommand command = new SqlCommand();
command.CommandText = "SELECT * FROM Product WHERE Product.ID=#PROD_ID";
command.Parameters.Add(new SqlParameter("#PROD_ID", 100));
// Execute the SQL Server command...
SqlDataReader reader = command.ExecuteReader();
DataTable tblProducts = new DataTable();
tblProducts.Load(reader);
foreach (DataRow rowProduct in tblProducts.Rows)
{
// Use the data...
}
It doesn't work because you are defining a parameter #name to your sql statement but you are never feeding any value since the version of SqlCommand.Parameters.Add that takes 2 parameters is the one that receives parameterName and SqlDbType
I am surprised you are not getting exceptions. Perhaps your dropdownlistname.SelectedValue matches one of the enumeration values for SqlDbType and that's why?
You should be doing:
ycmd.Parameters.AddWithValue("#name", dropdownlistname.SelectedValue);

Categories

Resources