How to select multiple options in a ListBox? - c#

I have a ListBox associated to a user. The user needs to be able to choose one or more options and save these options in the SQL database, but I can save only one option.
When I created my form I used the "enable postback option" and in my "selecction mode" I have: multiple.
Here is my code:
//IN MY FORM
if (!IsPostBack)
{
ClLinea_1 seleccion = new ClLinea_1();
DataSet ds = seleccion.sqlSelectLinea_1();
DataTable dt = ds.Tables[0];
ListBoxLinea_1.DataSource = dt;
ListBoxLinea_1.DataTextField = "descripcion";
ListBoxLinea_1.DataValueField = "id_linea_1";
ListBoxLinea_1.DataBind();
}
// IN MY BUTTON
protected void btnInsertaLinea_1_Click(object sender, EventArgs e)
{
ClLinea_1 inserta = new ClLinea_1();
inserta.SqlSeleccionLinea_1(int.Parse(ListBoxLinea_1.SelectedValue.),int.Parse
(txtUsuario.Text));
}

Well you need to make sure mulitiselect property is set to true.
Then use something like.
foreach(var item in MyListBox.SelectedItems)
{
int value;
if (int.TryParse(item.ToString(), out value)
{
// insert to db here.
}
}

Related

Assign a value to drop down list on page_load

I'm trying to assign value to a drop down list on the page_load, but it's not automatically get selected when the page loads up. But when I try to select another value from the drop down list, then the value assigned to it originally gets selected. I think it's something to do with the PostBack, My code is,
if (!string.IsNullOrEmpty(Request.QueryString["selectedReg"]))
{
string selectedReg = Request.QueryString["selectedReg"];
ddlVehicleReg.SelectedIndex = ddlVehicleReg.Items.IndexOf(ddlVehicleReg.Items.FindByText(selectedReg));
}
If I use if(!IsPostBack) still no luck, Any ideas? Thanks a lot in advance
The code block you have written is working. No need to check for postback. Be careful about your querystring. It looks like these pictures for my tests.
After your comment I changed dropdown item list. It is getting data from database. And I called this method in Page_Load
protected void Page_Load(object sender, EventArgs e)
{
FillDropDown();
if (!string.IsNullOrEmpty(Request.QueryString["selectedReg"]))
{
string selectedReg = Request.QueryString["selectedReg"];
ddlVehicleReg.SelectedIndex = ddlVehicleReg.Items.IndexOf(ddlVehicleReg.Items.FindByText(selectedReg));
}
}
protected void FillDropDown()
{
using (SqlConnection con= new SqlConnection("server=.;database=StackTest;integrated security=true") )
{
SqlDataAdapter adp = new SqlDataAdapter("select * from Test", con);
DataTable dt = new DataTable("Test");
adp.Fill(dt);
ddlVehicleReg.DataValueField = "Id";
ddlVehicleReg.DataTextField = "Value";
ddlVehicleReg.DataSource = dt;
ddlVehicleReg.DataBind();
}
}

add the new row client has entered to data source on radgirdview

I am new to using the telerik tools for winforms and I was wondering if anyone could help me to find the best way so that the client can add a new row on the radgrid and for it to show this change on the data source.
so far I have the radgrid set up so that the client can add a new row. I just need to bind it to the data source.
private void radGridView1_Click(object sender, EventArgs e)
{
this.radGridView1.AllowEditRow = false;
this.radGridView1.AllowAddNewRow = true;
this.radGridView1.AllowDeleteRow = false;
this.radGridView1.AddNewRowPosition = Telerik.WinControls.UI.SystemRowPosition.Top;
this.radGridView1.MasterTemplate.AddNewBoundRowBeforeEdit = true;
radGridView1.EnableAlternatingRowColor = true;
}
Have a look at the UserAddedRow event for RadGridView. This is fired after the user added a new row to the grid. You could then add the new entries to a source list or data table.
List<Foo> _lSource = new List<Foo>();
DataTable _tSource = new DataTable();
private void radGridView1_UserAddedRow(object sender, GridViewRowEventArgs e)
{
Foo foo = new Foo();
foo.Col1 = e.Row.Cells["col1"].Value.ToString();
foo.Col2 = e.Row.Cells["col2"].Value.ToString();
_lSource.Add(foo);
_tSource.Rows.Add(e.Row.Cells["col1"].Value.ToString(), e.Row.Cells["col2"].Value.ToString());
}
I added both possibilities in the same code snippet. Just choose one (list or table). I just created a random class to show you an example. You can create your own classes and name the properties as you want. Just note that the column (col1 and col2 in my example) must exist, otherwise you'll get a NullReferenceException. If you're using DataTable you have to add the columns once before adding rows.
_tSource.Columns.Add("col1");
_tSource.Columns.Add("col2");
I also recommend not to update the RadGridView properties on a click event of RadGridView. Because it is enough to set those properties once. Now you set them every time you click in your grid view. Either move them to the Load event of your form or set it directly in designer properties.
private void Form_Load(object sender, EventArgs e)
{
radGridView1.AllowEditRow = false;
radGridView1.AllowAddNewRow = true;
radGridView1.AllowDeleteRow = false;
radGridView1.AddNewRowPosition = Telerik.WinControls.UI.SystemRowPosition.Top;
radGridView1.MasterTemplate.AddNewBoundRowBeforeEdit = true;
radGridView1.EnableAlternatingRowColor = true;
}
RadGridView supports data binding to variety of data sources and CRUD operation will be handled for you automatically. Here you can find information on the supported data sources: Telerik UI for WinForms Documentation
And here is how to bind to a DataTable, where all CRUD operations work out of the box
RadGridView radGridView1 = new RadGridView();
this.Controls.Add(radGridView1);
radGridView1.Dock = DockStyle.Fill;
DataTable table = new DataTable();
table.Columns.Add("col1");
table.Columns.Add("col2");
table.Rows.Add("value1", "value1");
table.Rows.Add("value2", "value2");
radGridView1.DataSource = table;
Here is also a design time tutorial.

What is the most efficient way to sync two datagridviews?

Here is what I am trying to accomplish:
I have two datagriddviews. Datagridview1 holds a list of urls. Datagridview2 is basically a bookmarking system. A user can right-click on a url in datagridview1 and select to favorite or "bookmark" it. That row will then be copied to datagridview2. The font on the row on datagridview1 will then become bolded to show that it has been favorited and added to datagridview2. How do I keep these two synced? For example if a user removes a favorite on datagridview2 it should become unbolded on datagridview1 as it is no longer a favorite. What is an efficient way to keep these 2 synced to each other since the indexes will be different? I Had through about just iterating through each row to see if the cell content strings were equal and then unbolding it based off that but that seems very inefficient. Any suggestions on how to accomplish this?
As a good option you can have a data source like a DataTable having and string Url and a bool Favorite column.
Then, bind the first grid to the data table as its DataSource.
Bind the second grid to a DataView that you created from your data table and set Favorite=true as its Filter.
Then handle RowPrePaint event of first DataGridView and set the font to be bold if the row has favorite=true, else set the font to be regular.
For add button and remove button, set the value of favorite column on data row behind the current row and then call EndEdit on data row.
Initialization
private void Form1_Load(object sender, EventArgs e)
{
//Create DataTable
var data = new DataTable();
data.Columns.Add("Url", typeof(string));
data.Columns.Add("Favorite", typeof(bool));
//Fill Data
data.Rows.Add("http://stackoverflow.com", true);
data.Rows.Add("http://bing.com", false);
data.Rows.Add("http://google.com", false);
//Set DataBidnings to allUrlsDGV
this.allUrlsDGV.DataSource = data;
//Set DataBidnings to favoriteUrlsDGV
var favoriteData = new DataView(data);
favoriteData.RowFilter = "Favorite=true";
this.favoriteUrlsDGV.DataSource = favoriteData;
}
RowPrePaint
private void allUrlsDGV_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
var f = e.InheritedRowStyle.Font;
var drv = (DataRowView)allUrlsDGV.Rows[e.RowIndex].DataBoundItem;
if (drv.Row.Field<bool>("Favorite") == true)
allUrlsDGV.Rows[e.RowIndex].DefaultCellStyle.Font = new Font(f, FontStyle.Bold);
else
allUrlsDGV.Rows[e.RowIndex].DefaultCellStyle.Font = new Font(f, FontStyle.Regular);
}
Add and Remove Buttons
private void AddButton_Click(object sender, EventArgs e)
{
if (allUrlsDGV.CurrentRow == null)
return;
var drv = (DataRowView)allUrlsDGV.CurrentRow.DataBoundItem;
drv.Row["Favorite"] = true;
drv.Row.EndEdit();
}
private void RemoveButton_Click(object sender, EventArgs e)
{
if (favoriteUrlsDGV.CurrentRow == null)
return;
var drv = (DataRowView)favoriteUrlsDGV.CurrentRow.DataBoundItem;
drv.Row["Favorite"] = false;
drv.Row.EndEdit();
}

C# Textbox with databinding is not updating

I have a classic Form with 3 textboxes and 1 combobox. Combobox shows list of Users and 3 textboxes should contain details about the selected user in the combobox. For selected user I have a special attribute (as shown below) which I am using as data source. This is ok only on the first run. When the form is shown, changing user in combobox has no effect.
public partial class UserAdministration : Form
{
private readonly DataManager _dataManager = DataManager.Instance;
private User _selectedUser;
public UserAdministration()
{
InitializeComponent();
}
private void UserAdministration_Load(object sender, EventArgs e)
{
AddUsers();
textBoxName.DataBindings.Add("Text", _selectedUser, "Name");
textBoxSurname.DataBindings.Add("Text", _selectedUser, "Surname");
textBoxPassword.DataBindings.Add("Text", _selectedUser, "Password");
}
private void AddUsers()
{
var users = _dataManager.UserProvider.GetAll().Select(pair => pair.Value).ToList();
comboBoxUsers.DataSource = new BindingSource { DataSource = users };
comboBoxUsers.DisplayMember = "ListViewText";
if (users.Count > 0)
comboBoxUsers.SelectedIndex = 0;
}
private void comboBoxUsers_SelectedIndexChanged(object sender, EventArgs e)
{
_selectedUser = comboBoxUsers.SelectedItem as User;
}
}
What am I missing? What is wrong with data binding?
to bind your datasource to cb use this code:
comboBoxUsers.DataSource = users (directly to you datasource);
to bind the same data to textbox do it like this:
textbox1.DataBindings.Add("Text", users, "username", true);
the only point is, that you need to link both controls to the same ds instance
I have a form with ONLY a textbox that I wanted to bind to database column.
When I used the 'properties' settings to data-bind that textbox to one column, it created the bindingSource1 and table adapter for me.
When I clicked the SAVE button, I simply added bindingSource1.EndEdit(); and then it saved correctly to the database.

How to update DataGrid on click event?

I have the following code which updates the data base on a button click by calling a function additems.
static DataTable additems(string itema, string itemb, string itemc, string itemd)
{
DataTable listitems = new DataTable();
listitems.Columns.Add("itema");
listitems.Columns.Add("itemb");
listitems.Columns.Add("itemc");
listitems.Columns.Add("itemd");
// Add new items
listitems.Rows.Add(itema, itemb, itemc, itemd);
return listitems;
}
private void button1_Click(object sender, EventArgs e)
{
// add to data grid
dataGridView1.DataSource = additems("New text", "Almonds", "Butter", "Salt");
}
I wanted the above code to create new data grid. And it works fine for single data..
but for multiple data how can i achieve such heights?
I have a new variable (not using any database). Whenever button1 is clicked this variable needs to be loaded to data table so that it can instantly add to datagridview1.
I need some concepts...
well, you could change the method sig to take a new parameter for the datatable ...
if that's null, create a new table like you do now ... if it's not null, simply add a new row to that existing table
//quick and dirty example
static DataTable additems(string itema, string itemb, string itemc, string itemd, DataTable foo)
{
DataTable listitems = foo;
if(foo == null)
{
listitems = new DataTable();
listitems.Columns.Add("itema");
listitems.Columns.Add("itemb");
listitems.Columns.Add("itemc");
listitems.Columns.Add("itemd");
}
// Add new items
listitems.Rows.Add(itema, itemb, itemc, itemd);
return listitems;
}
private void button1_Click(object sender, EventArgs e)
{
// add to data grid
dataGridView1.DataSource = additems("New text", "Almonds", "Butter", "Salt", (DataTable)dataGridView1.DataSource);
}
you also might want to think about storing that datatable in a private field, instead of using (DataTable)dataGridView1.DataSource, but the question wasn't about good coding style ;)

Categories