How to convert Integer from database into string in textbox? - c#

This is a little piece of code I wrote to autocomplete my textbox from the database as I type:
{
SqlConnection connString = new SqlConnection();
connString.ConnectionString = "Data Source=************************;Initial Catalog=STUPELG;Persist Security Info=True;User ID=****************;Password=**********";
SqlDataAdapter adapter = new SqlDataAdapter();
connString.Open();
SqlDataReader dataReader;
SqlCommand command = new SqlCommand("SELECT Name FROM dbo.Entity WHERE Name LIKE #name", connString);
command.Parameters.Add(new SqlParameter("#name", "%" + tbEntity.Text + "%"));
command.ExecuteNonQuery();
dataReader = command.ExecuteReader();
AutoCompleteStringCollection col = new AutoCompleteStringCollection();
while (dataReader.Read())
{
col.Add(dataReader.GetString(0));
}
tbEntity.AutoCompleteCustomSource = col;
connString.Close();
}
However, I want to display two fields (EntityID, Name) out of the database into the textbox, but
I do not know how to display more than one field.
EntityID is an integer and I am not sure how to convert it to string in my code.
Any suggestions?

Usually a textbox is not used to display more than one data coming from the database. But also notice that autocomplete is a tool to help your end users to choose while typing.
If you want to add also the EntityID you need to add it after the name in the autocomplete source.
First you need to change the sql command to retrieve also the EntityID field and not just the Name field
string cmdText = "SELECT Name, EntityID FROM dbo.Entity WHERE Name LIKE #name";
SqlCommand command = new SqlCommand(cmdText, connString);
Then inside the loop that read the values you add both the Name and the EntityID as part of the string added to the autocomplete collection
while (dataReader.Read())
{
string data = $"{dataReader.GetString(0)} {dataReader.GetInt32(1)}"
col.Add(data);
}

Related

C# : querying multiple columns into textboxes

This is my code, and I want to be able to search for a name, and then pull from the database the name, status, member_id into the textboxes in my form.
I got the name to work but how do I get the other columns and parse the output into the textboxes with the additional columns (member_id, status)? Let's say the other textboxes have the standard name such as textbox2, 3, 4...
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
string sql1 = null;
SqlDataReader dataReader;
connetionString = "Data Source=......"
sql = "SELECT NAME FROM Test_Employee WHERE Name LIKE '" + textBox1.Text.ToString() + "%'";
connection = new SqlConnection(connetionString);
{
connection.Open();
command = new SqlCommand(sql, connection);
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
textBox9.Text = dataReader[0].ToString();
textBox7.Text = dataReader[0].ToString();
}
connection.Close();
}
Are the fields Member_Id and Status also in the table Test_Employee? You can add them in your Select statement and get them from your SqlReader, like the code below (assuming you are using c#7 and below). You may copy and paste this code.
var connectionString = "";
var sql = #"SELECT TOP 1 Name, Member_Id, Status
FROM Test_Employee
WHERE Name LIKE #name + '%'";
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.Add("name", SqlDbType.NVarChar, 100).Value = textBox1.Text.ToString();
connection.Open();
var reader = command.ExecuteReader();
if (reader.Read())
{
textBox9.Text = dataReader["Name"].ToString();
textBox7.Text = dataReader["Name"].ToString();
textBox2.Text = dataReader["Member_Id"].ToString();
textBox3.Text = dataReader["Status"].ToString();
}
}
You will notice that instead of including the Textbox1.Text's value in your Select statement, it is added as a parameter in the SQLCommand object's Parameters. In this way your query is protected from SQL Injection. If you want to learn more, you can search c# sqlcommand parameters and why it is very important to build data access code this way.
Also, notice that I added Top 1 in your Select statement, and instead of using while, I am using if. This is because a textbox can only hold 1 result at a time in a comprehensible way. If you meant to show multiple results clearly, you need to use a different control other than a TextBox.
The using statements allow you to dispose the connection, so you don't have to call connection.Close().

How to search a word inside a string where word is in a SQL Server table

I have a SQL Server table with two columns Keyword and Emotion.
I want to search a word (which is specified in column Keyword) inside a string which contains a sentence.. for eg:- How are you
I want to execute two queries:
I want to search if the string contains "how" (how is specified in Keyword column)..
If the string contains how, I want to display the corresponding value stored in the Emotion column of the table
This is my sample code (which can be completely wrong :p):-
public partial class message : System.Web.UI.Page
{
string constring = ConfigurationManager.ConnectionStrings["AnonymiousSocialNetworkConnectionString"].ToString();
protected void btnsend_Click(object sender, ImageClickEventArgs e)
{
SqlConnection con = new SqlConnection(constring);
string value = txtmsg.Text;
con.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select emotion from messageanalysis where keyword CONTAINS'",con);
myReader = myCommand.ExecuteReader();
while(myReader.Read())
{
lblStatus.Text = myReader["emotion"].ToString();// **this label should Display corresponding value stored in Emotion(column)**//
}
}
}
You just need only one SQL command and that should be like below -
string searchParam = "hello";
SqlCommand myCommand = new SqlCommand("select emotion from messageanalysis where CONTAINS(keyword,#SearchParam)",con);
myCommand.Parameters.Add("#SearchParam", System.Data.SqlDbType.VarChar, 20).Value = searchParam,;
CONTAINS may not work if full-text feature is not enabled on server. Please check this link for more details - Cannot use a CONTAINS or FREETEXT predicate on table or indexed view because it is not full-text indexed
If you do not want to enable this feature then use LIKE -
SqlCommand myCommand = new SqlCommand("select emotion from messageanalysis where keyword like #SearchParam)",con);
myCommand.Parameters.Add("#SearchParam", System.Data.SqlDbType.VarChar, 20).Value = "%" + searchParam + "%";

loop through all values in sql table using sql data reader

I want to fetch all rows that related to the query below, my problem that only one row retrived not all rows , iam using asp.net with c# and ado.net and my code logic is
if (!IsPostBack)
{
string username = Session["username"].ToString();
con.Open();
string strqryScript = "select * from dbo.teachers where user_id = '" + username + "'";
SqlCommand cmd = new SqlCommand(strqryScript, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataReader rdr = cmd.ExecuteReader();
rdr.Read();
string name = rdr["teach_id"].ToString();
rdr.Close();
string query = "select * from dbo.teacher_classes where teach_id = '" + name + "' ORDER BY class_id";
SqlCommand cmd2 = new SqlCommand(query, con);
SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
SqlDataReader rdr2 = cmd2.ExecuteReader();
while (rdr2.Read())
{
classname.Text = rdr2["class_id"].ToString();
}
con.Close();
}
extra note that i can use gridview to bind data but i want to fill my table with custom information from many tables , so i want to use an html table and fill it with my custom data. any help please! and thanks ..
While looping on the second reader, you write the value extracted from the reader on the Text property of the classname label. This will overwrite the previous text and leave you with the name of the last teacher retrieved. You need to add to the previous text or use a List.
classname.Text += rdr2["class_id"].ToString();
Said that, let me point you to a big problem in your code. String concatenation is really bad when you build sql commands. It gives you back syntax errors (if your input text contains single quotes) or Sql Injection as explained here
You should use parameterized queries like this (just for your first command)
string strqryScript = "select * from dbo.teachers where user_id = #id";
SqlCommand cmd = new SqlCommand(strqryScript, con);
cmd.Parameters.AddWitValue("#id", username);
....
This is the issue you need to fix:
classname.Text = rdr2["class_id"].ToString(); <== always setting the same text!!
You need to make sure, you fill a list, a dataset or whatever, when reading the data!

Storing table column value into variable (SQL Server)

I have been stuck on this problem for some time: I am trying to save a value from a column in a table (database), under a certain condition.
In the code below I am trying to compare the input of a textbox (sUserName) with a value in a column (UserName) in the table (aspnet_Membership). If these values are equal, I want to fetch the specific Email value in a column and save it as a string variable.
If UserName (column) does not equal sUserName (textbox), then I would like to display an error message (else statement). The Email and UserName column are in the same table
string sUserName = txtBoxUsername.Text;
SqlConnection conn2 = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\sunny\Visual Studio 2010\Projects\email\Prac 2\App_Data\aspnet_Membership.mdf;Integrated Security=True;User Instance=True");
SqlCommand myCommand = new SqlCommand("SELECT Email FROM aspnet_Membership WHERE UserName = sUserName", conn2);
Just add checking if user exist on your table to your code something like:
string sUserName = txtBoxUsername.Text;
SqlConnection conn2 = new SqlConnection("Your SQL Connection");
SqlCommand myCommand = new SqlCommand("SELECT Email FROM aspnet_Membership WHERE UserName = '"+ sUserName + "'", conn2);
SqlDataReader rdr = myCommand.ExecuteReader();
if (dr.HasRows)
{
while (rdr.Read())
{
// User exist - get email
string email = rdr["Email "].toString();
}
}
else
{
//Error! user not exist
}
Best Regards

What would cause the SelectedValue control not to work?

I am having an issue with the SelectedValue control. I have first created a comboBox, and tied to it is the following method:
private void Form1_Load(object sender, EventArgs e)
{
SqlCeConnection cn = new SqlCeConnection(#"Data Source = \Program Files\ParkSurvey\ParkSurvey.sdf; Persist Security Info = False; Password = *");
cn.Open();
SqlCeCommand cmd = cn.CreateCommand();
cmd.CommandText = "SELECT Name FROM Cities ORDER BY Name ASC";
SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
cn.Close();
cboCities.ValueMember = "CityId";
cboCities.DisplayMember = "Name";
cboCities.DataSource = ds.Tables[0];
cboCities.SelectedIndex = -1;
}
Assuming this is the only code I have present in my form, the comboBox (cboCities) populates accordingly. My issue arises when I try to fill a second comboBox (cboParks) with the corresponding parks associated with that city. This method looks as follows:
private void cboCities_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboCities.SelectedIndex > -1)
{
SqlCeConnection cn = new SqlCeConnection(#"Data Source = \Program Files\ParkSurvey\ParkSurvey.sdf; Persist Security Info = False; Password = *");
cn.Open();
SqlCeCommand cmd = cn.CreateCommand();
cmd.CommandText = "SELECT Name FROM [Parks] WHERE CityId =" + cboCities.SelectedValue + " ORDER BY Name ASC";
SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
cn.Close();
cboParks.ValueMember = "ParkId";
cboParks.DisplayMember = "Name";
cboParks.DataSource = ds.Tables[0];
cboParks.SelectedIndex = -1;
}
}
When I load up my Mobile Application, the first comboBox does not populate correctly and is in fact displaying data along the lines of: "System32.Data....", and when selecting any of them, I am brought to the runtime error that states “There was an error parsing the query. [Token line number = 1, Token line offset = 52,Token in error = Data]”. I have been lead to believe the issue itself is from the SELECT statement here:
cmd.CommandText = "SELECT Name FROM [Parks] WHERE CityId =" + cboCities.SelectedValue + " ORDER BY Name ASC";
When I change the cboCities.SelectedValue to cboCities.SelectedItem, the comboBox cboParks populates appropriately minus the filtering (it brings back ALL the data). I can also change it to simply CityId (for testing purposes) and the SELECT statement works.
I have also tried to paramertize it as such, but am brought to an entirely different error: "No mapping exists from DbType System.Data.DataRowView to a known SqlCeType."
cmd.CommandText = "SELECT Name FROM [Parks] WHERE CityId = #CityId ORDER BY Name ASC";
cmd.Parameters.AddWithValue("#CityId", cboCities.SelectedValue);
Basically, what is causing SelectedValue NOT to work and bring back the appropriate CityId ValueMember of the first method? I am pulling my hair out trying to figure this out. Also, if anyone has another method of binding selected data to comboBoxes, then please do share! I'm new to the C# world so any help is much appreciated. Thank you.
As from MSDN,
The SelectedValue return the value of the member of the data source specified by the **ValueMember** property.
You specify as ValueMember the field CityID, but in your query this field is not present.
Therefore the SelectedValue returns the result of the ToString() method of the object.
that happens to be a System.Data.DataRowView.
I think you could resolve your problem simply adding that field to your query
So change your code in this way
using(SqlCeConnection cn = new SqlCeConnection(#"Data Source = \Program Files\ParkSurvey\ParkSurvey.sdf; Persist Security Info = False; Password = *"))
{
cn.Open();
SqlCeCommand cmd = cn.CreateCommand();
cmd.CommandText = "SELECT CityID, Name FROM Cities ORDER BY Name ASC";
SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
}
....
then you will be able to use parameters on the second query.
Your Select Statement that fills the Combobox is wrong
cmd.CommandText = "SELECT Name FROM Cities ORDER BY Name ASC";
Should be
cmd.CommandText = "SELECT Name, CityID FROM Cities ORDER BY Name ASC";

Categories