In C#, How to use Selected Index with Combobox and Textbox - c#

Using selectedIndexChange for Combobox to fill Textboxes in Access Database.
I've tried using the following:
txtEventDate.Text = cboEventName.SelectedValue.ToString();
but it doesn't fill in from the selected data.
// clear out listbox
cboEventName.Items.Clear();
// create instance of class
clsData myData = new clsData();
// send SQL statement to class
myData.SQL = "SELECT ID, EventName, EventDate FROM tblEvents ORDER BY EventName";
// loop through datatable to get values
for (int i = 0; i < myData.dt.Rows.Count; i++)
{
// add customer to list box
cboEventName.Items.Add(myData.dt.Rows[i]["EventName"].ToString());
// add customer id to list
string eventdate = ["EventDate"].ToString();
txtEventDate.Text = cboEventName.SelectedValue.ToString();
// txtEventDate trying to fill from combobox entry and it isn't showing the date from the access.
intEventID.Add(int.Parse(myData.dt.Rows[i]["ID"].ToString()));
}

Try like this to set EventDate for Selected Index value. If SelectedValue is Matching to MyData Row Index then set event Date.
for (int i = 0; i < myData.dt.Rows.Count; i++)
{
// add customer to list box
cboEventName.Items.Add(myData.dt.Rows[i]["EventName"].ToString());
// add customer id to list
if(cboEventName.SelectedValue.ToString() ==myData.dt.Rows[i]["EventName"].ToString())
string eventdate = ["EventDate"].ToString();
txtEventDate.Text = cboEventName.SelectedValue.ToString();
}

Related

How to set Item checked in a checkedlistbox based on Key value?

I have checkedListbox for which i am binding values with Id and Values, when the items are checked i'm saving the Id's in the database, when the form loads i want the checkedListbox items to be checked based on the Id's
I am only able to bind the checkedlistbox based on the index as below , the other alternative i see is getting the Index of the value and checking it but this will not work in my case as i have only the Id's of the checkedlistbox items which needs to be checked.
int index = checkedListBox1.Items.IndexOf("42");
checkedListBox1.SetItemChecked(index , true);
this is how I am binding values
ccBoxitem item = new ccBoxitem(a.name, a.id);
checkedListBox1.items.add(item);
public ccBoxitem (string name, int val)
{
this.name = name;
this.val = val;
}
How can I check the checkedlistbox based on the id's ?
For example, you can loop through your items, then check the one you want:
private void CheckItem(int id)
{
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
if ((checkedListBox1.Items[i] as ccBoxitem)?.val == id)
{
checkedListBox1.SetItemChecked(i, true);
}
}
}
usage:
var id = GetId();
CheckItem(id);
You can use below method it will select needed item by its value first then check the selected item
void CheckItem(CheckedListBox checkedListBox, int id)
{
checkedListBox.SelectedItem = checkedListBox.Items.OfType<ccBoxitem>().ToList().FirstOrDefault(i => i.val == id);
checkedListBox.SetItemChecked(checkedListBox.SelectedIndex, true);
checkedListBox.SelectedItem = null; // To clear selection if needed
}
And you can call it as below
CheckItem(checkedListBox1, 3);
CheckItem(checkedListBox1, 6);

Set selected value in dynamically created combo boxes

I have created dynamic combo boxes but i am not able to set the value of the combo box
var list = new List<string>() { "Add","Sub","Mul","Div"};
for (int i = 0; i < 10; i++)
{
var c = new ComboBox();
c.DataSource = list.ToList();
c.selectedvalue="Sub";
this.flowLayoutPanel1.Controls.Add(c);
}
You are setting the DataSource of your ComboBox and trying to set the SelectedValue but for this to work correctly you need to set the ValueMember to the name of a member property of your datasource. But, in your case, having a simple list of strings, you cannot use any meaningful property name for SelectedValue.
Change your code to
List<string> list = new List<string>() { "Add","Sub","Mul","Div"};
for (int i = 0; i < 10; i++)
{
var c = new ComboBox();
c.Items.AddRange(list.ToArray());
c.SelectedIndex = 1;
this.flowLayoutPanel1.Controls.Add(c);
}
Of course you could make this more generic using the IndexOf("Sub") to retrieve the index and replace the fixed 1 that I have used, but in this case it seems useless.
To select a default value of a combobox use the below code.
c.SelectedIndex = 1;
This will set the start position at the first item in your list.

Add items and value of the drop down list from the database

I used this c# code to add items in dropdownlist(ddlSub) from the table sub_info. But what I want is to add the value of the items in dropdownlist(ddlSub) from the same table which also has a column named sub_id of datatype varchar(50).
private void bind_ddlSub()
{
ddlSub.Items.Insert(0, "-Choose-");
datatable_object = methodClassFunc.getData("select sub_name from sub_info");
for (int i = 0; i <= datatable_object.Rows.Count - 1; i++)
{
ddlSub.Items.Add(Convert.ToString(datatable_object.Rows[i]["sub_name"]));
}
}
You can use the ListItem object to add text and value for a dropdownlist item.
string subname = datatable_object.Rows[i]["sub_name"];
string subid = datatable_object.Rows[i]["sub_id"];
ddlSub.Items.Add(new ListItem(subname,subid));
Or you can bind your datasource like this:
ddlSub.DataSource = datatable_object;
ddlSub.DataTextField = "sub_name";
ddlSub.DataValueField = "sub_id";
ddlSub.DataBind();
You can do:
for (int i = 0; i <= datatable_object.Rows.Count - 1; i++)
{
ddlSub.Items.Add(new ListItem(Convert.ToString(datatable_object.Rows[i]["sub_name"]),
Convert.ToString(datatable_object.Rows[i]["sub_id"]));
}
Or you can bind the DataTable to your DropDownList and the specify DataTextField for display and DataValueField to get the value on index changed event like:
ddlSub.DataSource = datatable_object;
ddlSub.DataTextField = "sub_name";
ddlSub.DataValueField = "sub_id";
ddlSub.DataBind();

Saving for loop values to database

I have a gridview to insert values into database, but it's always showing the latest value (i tested using label). I want to have it to input all the values in database (multiple rows) values of each row in grid view to be inserted into multiple rows in the database.
Here's my grid view:
I need to save every row's value into the database. Here's my code:
protected void btnCreate_Click(object sender, EventArgs e)
{
if (int.TryParse(testLabel.Text, out number))//Click count
{
testLabel.Text = (++number).ToString();
}
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
TextBox box1 = (TextBox)GridView1.Rows[i].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)GridView1.Rows[i].Cells[2].FindControl("TextBox2");
Model.question act = new Model.question(); // Entity Model CRUD
act.Answer = box2.Text; //Always show the last value.
act.QuestionContent = box1.Text; // Always show the last value.
act.TaskName = "Grammar";
act.ActivityName = dropListActivity.SelectedItem.Text;
act.QuestionNo = testLabel.Text;
daoQuestion.Insert(act);
}
daoQuestion.Save();
}
}
TextBox1 and TextBox2 are the same throughout your Grid. By selecting TextBox1 and TextBox2 from different grid doesn't help, you'll just get the values from the same two TextBoxes.
Try adding the TextBoxes to a List and then subsequently, just get their Text and insert into your database.
To add TextBox into a list, you can do this.
List<TextBox> tbList = new List<TextBox>();
tbList.Add(new TextBox{ Name="textbox"+i++ });
Subsequently, to grab the values out, just do this.
for(int i = 0; i < tbList.Count; i++)
{
//To see the data you're inserting into database.
Response.Write(tb[i].Text);
Response.Write(tb[i+1].Text);
//Insert into database based on your code.
daoQuestion.Insert(new Model.question
{
Answer = tb[i].Text,
QuestionContent = tb[++i].Text,
TaskName = "Grammar",
ActivityName = dropListActivity.SelectedItem.Text,
QuestionNo = testLabel.Text
});
daoQuestion.Save();
}

Getting index for multiple selected item in ListBox in c#

I have two ListBoxes. First ListBox items are list of "Products". and second ListBox items are list of "Item in Product" so When user click the item in first(Product) Listbox The second ListBox will show the list of items in selected Products.
eg:
Products Items in Proucts
AA* 1
BB 2
CC 3
in example above current user selected AA products. And 1,2,3 are the items in product AA.
For the current program,i've done. User only can select One "Products" at a time. Then i want to change to multipleselected. So i want to get index number for each product that user selects, then i can retrieve data from database to get "Items In Products" for all selected products.
if (productsListBox.SelectedItmes.Count >= 0)
{
// please provide me coding here to get index number for each selected items in productListBox.
}
i already getting the answer:
if (productListBox.SelectedItems.Count >= 0)
{
for (int i = 0; i < productListBox.SelectedItems.Count; i++)
{
MessageBox.Show(productListBox.SelectedIndices[i].ToString());
}
}
if (productsListBox.SelectedItmes.Count >= 0)
{
string IDs = string.Empty;
foreach( ListItem li in productsListBox.SelectedItmes )
{
IDs += li.Value+"," ;
}
IDs = IDs.Trim(',');
}
It'll give you a CSV of selected IDs
private string GetTagsList()
{
string Tags = string.Empty;
if (lstTags.SelectedItems.Count >= 0)
{
for (int i = 0; i < lstTags.SelectedItems.Count; i++)
{
Tags += lstTags.SelectedIndices[i].ToString() + ",";
}
Tags = Tags.Trim(',');
}
return Tags;
}

Categories