I have created a MySQL table. I can insert Data but now I'd like to get the saved data after I enter it into another tab's TextBox in my Windows Application in c# language.
I have coded the button "Refresh" to get the data, but I dont know if its correct or not. Basically I want to click it, get the data from the table, and post it at the textbox.
Here is what I got so far for the getting data part:
private void button3_Click(object sender, EventArgs e)
{
string clanname, date, type, rules, final;
string connString = "Server=localhost;Database=request;Uid=root;Pwd=;";
using (MySqlConnection mcon = new MySqlConnection(connString))
using (MySqlCommand cmd = mcon.CreateCommand())
{
mcon.Open();
cmd.CommandText = "SELECT * FROM requesttcw";
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
clanname = textBox1.Text.Trim();
date = textBox2.Text.Trim();
type = textBox2.Text.Trim();
rules = textBox2.Text.Trim();
}
}
}
}
Please help!
Thanks
The Select query in your question is fetching data from your requesttcw table. You will want to read that data from your reader instance and add it to the appropriate text boxes. For instance, you could do something like this to get data:
//textBox1 will hold the value of the first row and first column of your database.
textBox1.Text = reader.GetString(0);
Updating the index in the GetString command above will change the column from which you are fetching data. So, you will have to update that index appropriately to fetch the proper data from your table and insert to the right text box's .Text property.
I don't know what type of data you are dealing with in your table. If the type is something other than string, you will want to use the appropriate Get function for the type, whether int, double, etc. Check out the MySqlDataReader reference page for more types.
Depending on the frequency of which your table layout changes, you may also want to use .GetOrdinal to get data using your reader. This command lets you specify a column name instead of its index. The above call could be changed to:
//assuming "clanname" is a column in your database
textBox1.Text = reader.GetString(reader.GetOrdinal("clanname");
Lastly, in your example you used
while (reader.Read()) { ... }
This will loop through each row in your query result set. I don't know how many text boxes you have or if you are looking for a specific format, but be aware that if you want to show data for a field from multiple rows in your text boxes, you will have to append to the Text property for each loop iteration.
Related
I know it's been asked many times and there's so many resources about this but believe me i tried those, Unfortunately same thing is always happen. I really don't know why my combo box column value is repeating. Can someone help me in doing these in a proper way. Did i forgot something here ? Thank you
public void FillComboBox()
{
using (var con = SQLConnection.GetConnection())
{
using (var cmd = new SqlCommand("SELECT * FROM employee_product", con))
{
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
cbox_order.Items.Add("Code").ToString();
cbox_order.Items.Add("Model").ToString();
cbox_order.Items.Add("Itemdescription").ToString();
}
}
}
}
}
Here's the provided image
If you check the code, you are basically just adding the strings "Code", "Model" and "Itemdescription" to the combobox. I guess you want rather something like:
while (reader.Read())
{
cbox_order.Items.Add($"{reader["Code"]} {reader["Model"]} {reader["Itemdescription"]}");
}
In this snippet I am using the reader to get values of the columns in the returned row from the DB and then displaying joining those values in a single string that is then added to the ComboBox as an item.
Update
If you know the column names, why not just do this?
public void FillComboBox()
{
cbox_order.Items.Add("Code").ToString();
cbox_order.Items.Add("Model").ToString();
cbox_order.Items.Add("Itemdescription").ToString();
}
First load data into a DataTable:
var connection = #"Your connection string";
var command = "Your SELECT command text";
var table = new DataTable();
using (var adapter = new SqlDataAdapter(command, connection))
adapter.Fill(table);
To show list of columns in a ComboBox:
comboBox1.DataSource = table.Columns.Cast<DataColumn>().ToList();
comboBox1.ValueMember = "ColumnName";
comboBox1.DisplayMember = "ColumnName";
To show data in DataGridView:
dataGridView1.DataSource = table;
In above code I suppose you are going to show columns of the table which you also want to load its data at the same time. In case which you just want to load just column information, you can use:
adapter.FillSchema(table, SchemaType.Mapped);
actually your not using your DataReader but you just add Code, Model and ItemDescription item for each row found with the MySQL query.
cbox_order.Items.Add("Code").ToString();
cbox_order.Items.Add("Model").ToString();
cbox_order.Items.Add("Itemdescription").ToString();
If you want to use the result of the MySQL query you can try this instead:
cbox_order.Items.Add(reader["Code"].ToString()).ToString(); // Change "Code" by the column name into the database
cbox_order.Items.Add(reader["Model"].ToString()).ToString(); // Change "Model" by the column name into the database
cbox_order.Items.Add(reader["Itemdescription"].ToString()).ToString(); // Change "Itemdescription" by the column name into the database
Don't forget to close the reader at the end
reader.Close();
EDIT
if you want the column name instead of data you can use this query, but that's useless if you already know the column name.
SELECT COLUMN_NAME FROM information_schema.columns WHERE table_schema='databasename' AND table_name='tablename'
Try to close and dispose of reader and close the connection.
reader.close;
reader.dispose;
con.close();
I'm fairly new to coding so am probably missing something obvious. I've tried searching here and various other resources but can't get my code to do what I want so I'm hoping someone can help.
I have a checkbox list which is populated from a SQL query based on user input.
My intention is that a user can check one or more items on the list and a SQL stored Procedure will be run for each checked item with the value of the selected item passed as a parameter value.
So, if there are six items in the list and three are checked my code will loop through the list and for each checked item will run the SP with the item's value as the parameter value before moving on to the next item in the list.
As a first step in testing the logic I have the code below which is supposed to pass a selected item's text to a label when a button is clicked, however rather than the checked box's text value I am just getting 'System.Data.DataRowView'
int checkCount = chckList.Items.Count;
for (int i = 0; i < checkCount; i++)
{
if (chckList.GetItemChecked(i))
{
String str = chckList.Items[i].ToString();
label23.Text = str;
}
}
If I change the assignment of the String str value to 'String str = chckList.GetItemText(i).ToString();' I just get the number of the item (i.e. if there are six values and the fist is checked then I get '0', if the second is checked I get '1', etc.)
The CheckBoxList is, as I've said, filled from a SQL query based on user input, my method for doing this is:
connection.Open();
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
DataTable datTbl = new DataTable();
adapter.SelectCommand = myCommand;
{
adapter.Fill(datTbl);
chckList.DataSource = datTbl;
chckList.DisplayMember = datTbl.Columns[1].ColumnName;
}
}
connection.Close();
Can anyone help? What am I doing wrong?
Thanks
If your Items are a collection of DataRowView objects, then this just gets a specific DataRowView and calls ToString() on it, which returns the fully qualified name of the object:
String str = chckList.Items[i].ToString();
Try accessing a specific column:
String str = ((DataRowView)chckList.Items[i])["SomeColumnName"].ToString();
I have a dropdownlist of zipcodes.
It is a really large list and takes too long to load from database. So, first I was looking for the best solution to try and cache or save this data when the website is first loaded so I can use it whenever needed. I tried a list and dictionary then setting the datasource in code behind but it wouldn't let me set the selected value.
It kept telling me that it couldn't bind to a control with no datasource. To make things more difficult the dropdownlist is inside a formview.
I am just not sure the best way to go about this. I am setting the datasource and values in the formview created method but my selected value comes from the formview datasource.
private Dictionary<int, string> CreateZipcodeList()
{
string connStr = ConfigurationManager.ConnectionStrings["KlamathAlgaeEntityDevConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
Dictionary<int,string> ziplist = new Dictionary<int,string>();
//Create CoreEntity Record
SqlCommand cmd1 = new SqlCommand(#"select zipcode.ZipCodeId, zipcode.zip + ', ' + city.name + ', ' + ISNULL(GeographicState.name,'') + ', ' + Country.name as zipstring
from zipcode left outer join City on ZipCode.CityId = city.CityId
left outer join GeographicState on ZipCode.GeographicStateId = GeographicState.GeographicStateId
left outer join Country on ZipCode.CountryId = Country.CountryId
order by country.name, GeographicState.name, city.name",
conn);
try
{
conn.Open();
SqlDataReader reader = cmd1.ExecuteReader(CommandBehavior.CloseConnection);
while (reader.Read())
{
if (!reader.IsDBNull(0))
{
ziplist.Add(reader.GetInt32(0), reader["zipstring"].ToString());
}
}
}
finally
{
if (conn != null)
{
conn.Close();
}
}
return ziplist;
}
protected void AddressForm_ItemCreated(Object sender, EventArgs e)
{
((DropDownList)AddressForm.FindControl("Zipcodeddl")).DataSource = CreateZipcodeList();
((DropDownList)AddressForm.FindControl("Zipcodeddl")).DataTextField = "Value";
((DropDownList)AddressForm.FindControl("Zipcodeddl")).DataValueField = "Key";
((DropDownList)AddressForm.FindControl("Zipcodeddl")).DataBind();
//((DropDownList)AddressForm.FindControl("Zipcodeddl")).SelectedValue = Eval("zipcodeid").ToString();
}
This populates the dropdown fine but when I try setting the selected value it says the control is not databound. This also doesn't store the dictionary anywhere so I need to call the function to load dictionary when ever I need it.
Ok, that is way too many records for a drop down. Why don't you allow the user to enter 5 numberic characters, and then do an search on your Database by that number. I can't think of any reason you would have to put the entire zip code list in a drop down since no one is going to manually click down to find the one they want. I don't think it servers a usefull purpose, but if there is one let me know and I will try to figure out a solution.
Thats how the post office does it.
Update
To make this work, you would have a TextBox where a user could enter the zip code they think it is. Give them a button to click to search for that zip code.
Do an sql query to your database looking for that Zipcode.Zip, and if found, bring back all the data you need.
If it is not found what I would do is start removing the last character and do another search with a modified query with "Zipcode.Zip like '%modifiedZipCode%', and bring back the closest 10 or so options, and put those in a drop down menu.
If you remove one digit and the database could not find it you could go as far as you want removing characters, and rerunning the query until you got 10 or however many records you want. At some point removing digits will become pointless because the user obviously entered an incorrect zip code.
I have a ComboBoxColumn in my datagridview and the data that's bound to them is from another table. The data can be updated at any point so I want to update the data in the ComboBoxColumn automatically when the data is added/updated from another table.
I've tried using -
ScripterCombo.DataSource = updatedUserList;
updatedUserListis a list of the data that i want to apply to the ComboBoxColumn, I already set the DataSource of ComboBoxColumn. Unfortunately the ComboBoxColumn never update. I need to reload the entire application to view the changes.
UPDATE -
Sorry i'm not using a list to store the data, i'm using a string array. Basically i connect to the backend server and loop through all the names in the 'User' Column:
MySqlConnection(Constants.serverInfo))
{
getNumberOfUsers.Open();
using (MySqlCommand requestCommand = new MySqlCommand("SELECT COUNT(*) FROM userlist", getNumberOfUsers))
{
MySqlDataReader userReader = requestCommand.ExecuteReader();
while (userReader.Read())
{
iNumberOfUsers = userReader.GetInt32(0); // Pull the number of Owners from the backend.
strListOfUsers = new string[iNumberOfUsers]; // Make sure the owner list can hold the value pulled from the backend.
}
userReader.Close();
}
getNumberOfUsers.Close();
}
// Get the names of the users
using (MySqlConnection getUsersNames = new MySqlConnection(Constants.serverInfo))
{
getUsersNames.Open();
using (MySqlCommand requestCommand = new MySqlCommand("SELECT username FROM userlist", getUsersNames))
{
MySqlDataReader userReader = requestCommand.ExecuteReader();
for (int i = 0; i < iNumberOfUsers; i++)
{
while (userReader.Read())
{
strListOfUsers[i] = userReader.GetString(0); ; // Add the user to the list of users.
i++;
}
}
userReader.Close();
}
getUsersNames.Close();
}
I have another class that grabs data from a different table and displays it in a datagridview. I then feed the array of users through to the above class and create a datagridcomboboxcolumn that displays all the usernames. This works as expected, as it displays the user list and then updates the main table when a user has been changed.
However, if i add a user to the list I call the above code again to get an updated list and then feed the list to the comboboxcolumn using this -
ScripterCombo.DataSource = updatedUserList;
This unfortunatly doesn't update the comboboxes, but when I check the DataSource after running this it's showing the newly added user. It just doesn't want to display it.
Hope this makes sense.
Thanks
try to add ToList()
ScripterCombo.DataSource = updatedUserList.ToList();
i have some textboxes. in first textbox i entered a vaue like empid. after the clicking a button which goes to database and checks for the columns specified by me.
i get that data in datareader.
from datareader i need to display the particular employ information in the remaining textboxes.
how can i achieve this.
Assuming your datareader is called rdr, something like this would work:
while(rdr.Read())
{
txtBox1.Text = rdr.Item["DBFieldName1"].ToString();
txtBox2.Text = rdr.Item["DBFieldName2"].ToString();
}
while (dr.Read())
{
string checkValue = dr.GetValue(0).ToString();
if (checkValue == myEmpIdTextbox.Text)
{
Texbox2.Text = dr.GetValue(1).ToString();
Texbox3.Text = dr.GetValue(2).ToString();
}
}
Works in C# - Visual Studio 2015.
The values in the brackets () next to GetValue indicate the column number, relative to your SQL Select query.
EXAMPLE:
SELECT coloumn1, coloumn2, coloumn3 FROM table
Then, in this case, Textbox3.Text will be made equal to the data in coloumn3, and Textbox2. Text to coloumn2, for that row where coloumn1 is equal to your value in your Empid textbox.