Fill data to combobox from sql command [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm using below code but, it's giving me an error.
private void ma2()
{
try
{
string query = "select k7 from kholy1";
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandText = query;
con.Open();
SqlDataReader drd = cmd.ExecuteReader();
while (drd.Read())
{
comboBox5.Items.Add(drd.GetValue(0).ToString());
}
drd.Close();
}
catch
{
MessageBox.Show("Error ");
}
}
I'm getting an error while displaying the form!

You just simply use combo box tasks and check use Data Bound Items that's how you are able to connect it to sql database. Value member use to store it's value in database and Display Member use to Display value in front end.
You can use selected value using combobox1.SelectedValue.
Reference- Binding WPF ComboBox to a Custom List

Related

Search database for value and get info c# Forms [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a database called "users" where user information is saved. When you login with your name and pass, your name is send to the homeform, where i want to get the "to-do list" that's saved in the database with your info. Here's my code so far:
db_connection();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "SELECT * FROM `user` WHERE `username`=#username AND `todo`=#todo";
So basically i need to get the todo of the user (which is sent to this form as _name) lets say admin, and display it in tbTodo.
if it is in the same form you can try using
select `user`.todo from `user` where `username` = #username
considering username is unique
If the main problem is parameters - u can use property Parameters:
cmd.Parameters.AddWithValue("#username", user);
There is an example in msdn:
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("#ID", SqlDbType.Int);
command.Parameters["#ID"].Value = customerID;
// Use AddWithValue to assign Demographics.
// SQL Server will implicitly convert strings into XML.
command.Parameters.AddWithValue("#demographics", demoXml);
try
{
connection.Open();
Int32 rowsAffected = command.ExecuteNonQuery();
Console.WriteLine("RowsAffected: {0}", rowsAffected);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

Alert message when certain limit has been made [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am creating a form for alerting the user that the stock for this item in the database is getting the limit or passed right through the limit.
this is my code for checking the quantity of a certain stock
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "select * from tbl_BloodChemistry where Glucose = "+123+" ";
reader = cmd.ExecuteReader();
int count = 0;
while (reader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("Critical!");
}
conn.Close();
It's not actually the answer, but you have no reason to retrieve all data to collect count of rows. Use SQL COUNT and ExecuteScalar() for this.
Also, it's important to use command Parameters to your query. Don't ever build a query in your way! The input variable, Glucose, is typically retrieved from a TextBox control on either a Windows form or a Web Page. Anything placed into that TextBox control will be put into inputCity and added to your SQL string. This situation invites a hacker to replace that string with something malicious. In the worst case, you could give full control of your computer away.
Instead of dynamically building a string, as shown in the bad example above, use parameters. Anything placed into a parameter will be treated as field data, not part of the SQL statement, which makes your application much more secure.
Using parameterized queries is a three step process:
Construct the SqlCommand command string with parameters.
Declare a SqlParameter object, assigning values as appropriate.
Assign the SqlParameter object to the SqlCommand object's Parameters property.
var glucoseFilterValue = "123";
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "select count(*) from tbl_BloodChemistry where Glucose = #Glucose";
cmd.Parameters.AddWithValue("#Glucose", glucoseFilterValue);
var count = (int) cmd.ExecuteScalar();
if (count == 1)
{
MessageBox.Show("Critical!");
}
conn.Close();
Then you'll make your code more clean and prevent extra loading to your communication channel.

How to link database with C# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Okay, I am wanting to basically connect my windows form application in C# to my database, what I want it to do is display a random word from the database into the label of my form. When I say display a random word I mean display a random word from the 20 words in a table of my database. I was wondering how would you do this? I really dont want the answer as I want to learn, but could you explain how would I do this?
Thanks in advance:)
I am wanting to connect the database using Access rather than the framework provided by .NET
First of all I would like to suggest to use google first Beginners guide to connect SQL with C# then I would like you to post question regarding to one topic for instance - Connect SQL with C#. And the part with picking random word should be another solo question.
Anyway I hope this will work for you, but please, keep in mind that we are not here to code for you without any coding effort and your code.
My code:
List<string> wordList = new List<string>();
string connection = "YourConnectionString";
OleDbConnection con = new OleDbConnection(connection);
string query = "SELECT * FROM yourTable WHERE ID=#param"; // add as many conditions as you need
OleDbCommand comm = new OleDbCommand(query, con);
comm.Parameters.AddWithValue("#param", textBox1.Text); //example of parameter
con.Open();
OleDbDataReader rdr = comm.ExecuteReader();
while (rdr.Read()) //this will loop through all rows with given conditions.
{
wordList.Add(rdr.GetString(rdr.GetOrdinal("YourSQLColumn")).Trim());
}
con.Close();
Random rnd = new Random();
int randomint = rnd.Next(1, 20); // generates a random number between 1 and 20
label1.Text = wordList[randomint].ToString();
Here's a sample to get you started
public static void Main()
{
string connectionString = "data source=.\\SQLEXPRESS;Integrated Security=SSPI;database=InsertDatabaseNameHere; connection timeout=30";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlCommand command = new SqlCommand("select ColumnName from TableName", connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader.GetValue(0));
}
connection.Close();
}
Just set up a SQLDataReader and convert to a list...you just have a one-dimensional list of strings. You'll be looping through the results and adding them to a list. (There's probably a more elegant way to do this, but you've only got 20 strings, not 20,000, so I don't think you need to get crazy with this)
Here's another SO question to get you started...this answer is probably what you need.
You just set your Datareader up against Access (there's a bazillion hits on doing this), convert it to a list, and off you go...

Displaying a specific Date in a DropDown from a range Dates in asp.net: Object reference not set to an instance of an object Error [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I am trying to populate a dropdown , where I want the default selected value to be the sysdate selected. For example if I have 4 results in the dropdown
Wednesday,January 22,2013
Thursday,January 23,2013
Friday,January 24,2013
Saturday,January 25,2013
I want todays date Friday,January 24,2013 to be the default selected value. Now to achieve that I have written code like below in my method.
string DateofNow = DateTime.Now.ToString("dddd,MMMM dd,yyyy");
DataTable table = new DataTable();
string sqlQuery = "select distinct duty_date from duty_rota where duty_date BETWEEN SYSDATE - 40 AND SYSDATE + 365 order by duty_date";
using (OracleConnection conn = new AppConfig().GetConnection())
{
try
{
conn.Open();
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
using (OracleDataAdapter ODA = new OracleDataAdapter(cmd))
{
ODA.Fill(table);
}
}
}
catch (Exception ex)
{
Response.Write("Not Connected" + ex.ToString());
}
}
DropDownList1.DataSource = table;
DropDownList1.DataValueField = "duty_date";
DropDownList1.DataTextField = "duty_date";
DropDownList1.DataTextFormatString = "{0:dddd,MMMM dd,yyyy}";
DropDownList1.DataBind();
DropDownList1.Items.FindByText(DateofNow).Selected = true;
But I am getting "Object reference not set to an instance of an object" Error. I am clueless where I am going wrong exactly. Can somebody please help me in this.
Assuming you run the above code today, it's because DateofNow value is Friday,January 24,2014 but none of the DropDownList items has the exact same value. Since the query result may not contain today's date, I would suggest changing this line:
DropDownList1.Items.FindByText(DateofNow).Selected = true;
to this:
if (DropDownList1.Items.FindByText(DateofNow) != null)
{
DropDownList1.Items.FindByText(DateofNow).Selected = true;
}
so if the query result doesn't contain today's date, you won't get the same error again and the DropDownList won't select any of its items.

Is it possible to simultaneously select item in combobox and insert into different columns of database table? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am using C#.net. my query is: I have multiple items in my combobox, when i select 1st item , it should get inserted in column1 of database table,when i select 2nd item of the same combobox, it should get inserted in 2nd column of database table and so on..
How can I write the code for the same.
as you haven't provided any of your effor so the best i can do is to write a pseudo code for you.
string columnName = string.Empty;
if(myComboBox.SelectedIndex == 0)
columnName = "column1";
else if(myComboBox.SelectedIndex == 1)
columnName = "column1";
string myValue = "assign your value here";
string insertStatement = "insert into myTable("+columnName+") values(#param1)";
using(SqlConnection sqlCon = new SqlConnection("ConnectionString"))
{
sqlCon.Open();
SqlCommand cmd = new SqlCommand(insertStatement,sqlCon);
cmd.Parameters.Add("#param1", SqlDbType.Varchar, 50).value = myValue;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
You can use the SelectedIndex change event to capture the record selected and based on the index you can write the switch statement to insert in proper column
You Can try this for solve your problem :-
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (ComboBox1.SelectedIndex ==1)
{
// Your other code Column 1
}
if (ComboBox1.SelectedIndex ==2)
{
// Your other code Column 2
}
}
May be help you
You could pass the selected index to the database. You need to check the index value to set the value to the appropriate column from the database itself.

Categories