returning text values from CheckBoxList - c#

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();

Related

ComboBox SelectedItem Not Changing

Edit: I am using window forms
So, I want to change a value of NumericUpDown if the selected value in combo box changes.
I placed a data table items with the columns ID, itemName, itemPrice and Stock and set the DisplayMember property to itemName.
I used this code:
cmb.DisplayMember = "itemName";
cmb.DataSource = items;
Then to get the whole row of the selected item I used
DataRow dataRow = ((DataRowView)cmbItems.SelectedItem).Row;
The problem is that in the UI, the combo box's selected item does not changes no matter what I do but the value of the selected item changes.
Like this.
I first thought that my unit is just lagging but its not. How do I fix this?
You can try this code to check if the combobox will get the selected item when you make your option.
dbConn.Open();// this allows you to edit the database
string sql = "Select * from database1";
SqlCommand dbComm = new SqlCommand(sql, dbConn);
SqlDataAdapter dbAdapter = new SqlDataAdapter(dbComm);
DataTable dt = new DataTable();
dbAdapter.Fill(dt);
cmbDescription.DataSource = dt;
cmbDescription.DisplayMember = "itemName";
cmbDescription.ValueMember = "Enter the column name here";
cmbDescription.Text = "";
cmbDescription.Items.Add(dt);
cdbConn.Close(); //close connection to save all your inputs,calculations to the database
I found out that my code is very confusing and the system seem to be having problems while executing, I've rewritten the whole code for this window form and it is working now.

Why is 'DataView' row filter is only accepting two characters

I have a 'DataTable' populated with items from a SqlServer table. There are two columns in the 'DataTable': 'id' which is the identity value for the row in the SqlServer table and 'job' which is the name of an object.
I have a database client written in 'C#' using the '.Net' framework. It contains a 'ListBox', a 'TextBox', a 'DataTable', and a 'DataView'. The 'DataView' 'DataSource' is set to the 'DataTable'. The 'ListBox' 'DataSource' is set to the 'DataView'. There are 1700 rows in the table.
My preferred method of finding the correct item is for the user to begin to type in the textbox and as with each letter the list diminishes until the user can easily spot the desired one. The user can then double click on it and some action is taken. I have used this technique with 'BindingSource' and it works well. I am having trouble using with the 'DataView'. The first two letters the user types work well. But when the third letter is typed, the 'ListBox' goes blank, even though the filter string is correct. Why does it stop working with the third letter? Any help would be appreciated.
This is a sample of the data in the field 'job': '08-CBM-01 -- Water Utilities Topo Survey'
The data in the field 'id' is just an 'int' identity from SqlServer.
I've tried examining the variable strLookup and strFilter as entry is made using the keyboard and it appears these are correct.
DataTable tblSelectList;
DataView dvSelectList;
private string strFilter = "";
private string strLookup = "";
private void tbLookup_TextChanged(object sender, EventArgs e)
{
strLookup = tbLookup.Text.ToString();
if (strLookup.Length > 1)
{
strFilter = "job Like '%" + strLookup + "%'";
dvSelectList.RowFilter = strFilter;
}
else { dvSelectList.RowFilter = "job = 'z'"; }
btnDone.Enabled = false;
}
private void SetupLbSelect()
{
if (dvSelectList == null) { dvSelectList = new DataView(tblSelectList); }
lbSelect.DataSource = dvSelectList;
dvSelectList.RowFilter = "job = 'z'";
lbSelect.DisplayMember = "job";
lbSelect.ValueMember = "id";
}
No error messages. The ListBox begins to populate as expected with the 1st two characters and then goes blank with the third. I would expect to type 'Topo' and have all the items containing 'Topo' appear.
I deleted the procedure and several others from the code page and typed them in again. After that the function worked as expected. Thank you to LarsTech who told me the original code worked for him.

storing sql query results to populate dropdownlist inside formview

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.

Getting data from MySQL connection and showing it on a TextBox

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.

how to populate textboxes with values of datareader

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.

Categories

Resources