How to show grid row value in textBox on SelectionChanged event C#? - c#

I have to show the grid selected row value into textboxes.I'm using this code, but it's not working. Any help will be appreciated.
private void CRUD_SelectionChanged(object sender, EventArgs e)
{
txtBoxID.Text = CRUD.SelectedRows[0].Cells[0].Value.ToString();
txtBoxStates.Text = CRUD.SelectedRows[1].Cells[1].Value.ToString();
txtBoxName.Text = CRUD.SelectedRows[2].Cells[2].Value.ToString();
txtBoxAddress.Text = CRUD.SelectedRows[3].Cells[3].Value.ToString();
txtBoxCenter.Text = CRUD.SelectedRows[4].Cells[4].Value.ToString();
txtBoxCity.Text = CRUD.SelectedRows[5].Cells[5].Value.ToString();
}

You're indexing your selected rows. if you have less than 6 selected rows, then you will go out of bounds. You probably want to fetch data from only one row. Check if only one row is selected and then use index 0. Make sure you set CRUD.MultiSelect = false
Alternatively use CRUD.CurrentRow which will only ever get you one row.
Form.Designer.cs:
this.CRUD.SelectionChanged += new System.EventHandler(this.CRUD_SelectionChanged);
Form.cs:
private void CRUD_SelectionChanged(object sender, EventArgs e)
{
txtBoxID.Text = CRUD.CurrentRow.Cells[0].Value.ToString();
txtBoxStates.Text = CRUD.CurrentRow.Cells[1].Value.ToString();
txtBoxName.Text = CRUD.CurrentRow.Cells[2].Value.ToString();
txtBoxAddress.Text = CRUD.CurrentRow.Cells[3].Value.ToString();
txtBoxCenter.Text = CRUD.CurrentRow.Cells[4].Value.ToString();
txtBoxCity.Text = CRUD.CurrentRow.Cells[5].Value.ToString();
}

Related

C# Binding Source Control

I am Developing a winforms application. I have two datagrid views populated from two different bindingsources(control). I am using these to implement the master detail approach. My problem is that when the first datagridview is populated using the binding source I can't select the first row of it ,because the first element in the binding source is defaultly selected and can't be selected. Can any one provide me a solution for this
As you say the first row is selected by default. So after populating the DataSource to your first GridView you can set the second GridView based on first entry. Later you check the selectionChanged Event to populate the second GridView based on selectedRow of your first one.
Code could look sth. like this:
private void PopulateDataSource()
{
dataGridView1.DataSource = myBindingSource;
DataRowView selectedRow;
if (dataGridView1.SelectedRows.Count > 0)
selectedRow = dataGridView1.SelectedRows[0] as DataRowView;
if (selectedRow != null)
dataGridView2.DataSource = myBindingSource2; //Set the BindingSource based on selectedRow in first Grid
}
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
DataRowView selectedRow;
if (dataGridView1.SelectedRows.Count > 0)
selectedRow = dataGridView1.SelectedRows[0] as DataRowView;
if (selectedRow != null)
dataGridView2.DataSource = myBindingSource2; //Set the BindingSource based on selectedRow in first Grid
}
If this doesn't work let me know but should do the job.
UDPATE
Here is a similar example using the events and methods of the bindingSource:
private void Initialize()
{
RegisterBindingSourceEvents();
dataGridView1.DataSource = bindingSource1;
dataGridView2.DataSource = bindingSource2;
bindingSource1.DataSource = myDataSource;
}
private void RegisterBindingSourceEvents()
{
bindingSource1.DataSourceChanged += BindingSource1_DataSourceChanged;
bindingSource1.CurrentChanged += BindingSource1_CurrentChanged;
}
private void BindingSource1_CurrentChanged(object sender, EventArgs e)
{
DataRowView row = bindingSource1.Current as DataRowView;
if (row != null)
bindingSource2.DataSource = myDataSource2BasedOnRow;
}
private void BindingSource1_DataSourceChanged(object sender, EventArgs e)
{
DataRowView row = bindingSource1.Current as DataRowView;
if (row != null)
bindingSource2.DataSource = myDataSource2BasedOnRow;
}
Further you maybe can use:
bindingSource.MoveNext();
bindingSource.MoveFirst();
To simulate focusing seconde row and directly first row. A bit ugly but i would guess this fires current_changed (untested). Better use first approach.
UDPATE-2
I'm sorry to tell you that this is not possible in a beautiful manner. The problem is that the Current Property of your bindingList is always set if your DataSource contains items. So if the user select the same row as the bindingSource Current Property contains your event won't get called. I found a solution which works in my example. You will need one gridEvent and maybe have to do some improvments but the idea should do the job. Sorry but without gridEvent i can't solve this:
Notice that iam using List as DataSource for my Testcase. You got DataTable and have to cast to DataRowView instead of Dummy for sure.
private bool _automatedRowChange;
private void Initialize()
{
List<Dummy> dummies = new List<Dummy> { new Dummy { Id = 1, Text = "Test1" }, new Dummy { Id = 2, Text = "Test2" } };
bindingSource1.DataSource = dummies;
dataGridView1.DataSource = bindingSource1;
//So the first row isn't focused but the bindingSource Current Property still holds the first entry
//That's why it won't fire currentChange even if you click the first row. Just looks better for the user i guess
dataGridView1.ClearSelection();
bindingSource1.CurrentChanged += BindingSource1_CurrentChanged;
dataGridView1.CellClick += DataGridView1_CellClick;
}
private void DataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
var clickedRow = dataGridView1.Rows[e.RowIndex].DataBoundItem as Dummy;
var currentRow = bindingSource1.Current as Dummy;
if (clickedRow != null &&
currentRow != null &&
clickedRow.Equals(currentRow))
{
_automatedRowChange = true;
bindingSource1.MoveNext();
_automatedRowChange = false; //MovePrevious is based on the click and should load the dataSource2
bindingSource1.MovePrevious();
}
}
private void BindingSource1_CurrentChanged(object sender, EventArgs e)
{
if (!_automatedRowChange) //Check if you jump to next item automatically so you don't load dataSource2 in this case
{
//Set the second DataSource based on selectedRow
}
}

C# ComboBox SelectedItem.toString() not returning expected results

I have a form that allows a user to add players to a roster, by entering the player name and selecting, from a combo box, the division to which the player belongs.
When time comes to add the player to my TreeView control, the node that should display the division selected displays this text instead: System.Data.DataRowView
I got the code to implement this through MSDN here: https://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selecteditem%28v=vs.110%29.aspx
Here's the code in the load function of the form, to fill the combo box:
private void frm_add_players_Load(object sender, EventArgs e)
{
Divisions divs = new Divisions();
Players players = new Players();
DataTable dtDivisions = divs.GetActiveDivisions(); //divisions combo box
DataTable dtPlayers = players.GetPlayersByTourID(this.tourID);
//set the forms datatable
this.dt_players = dtPlayers;
//fill the combo box
this.cmbo_divisions.DataSource = dtDivisions;
this.cmbo_divisions.DisplayMember = "title";
this.cmbo_divisions.ValueMember = "ID";
this.cmbo_divisions.SelectedIndex = -1;
this.cmbo_divisions.Text = "Select a Division";
//set treeview imagelist
this.tview_roster.ImageList = tview_imagelist;
this.tview_roster.ImageIndex = 1; //division icon
//fill treeview
foreach (DataRow dr in dtPlayers.Rows)
{
FillPlayerTreeview(dr);
}
//expand treeview
this.tview_roster.ExpandAll();
this.ActiveControl = this.txt_player_name;
}
Here I call the function to add the player to the TreeView:
private void btn_add_Click(object sender, EventArgs e)
{
object selItem = cmbo_divisions.SelectedItem;
AddPlayerToTreeView(txt_player_name.Text, selItem.ToString());
}
And here is the function that adds the player:
private void AddPlayerToTreeView(string playerName, string division)
{
TreeNode[] tns = this.tview_roster.Nodes.Find(division, false); //try to find the division, if exists
TreeNode tn = new TreeNode();
if (tns.Length > 0) //division exists - add player
{
tn = this.tview_roster.Nodes[tns[0].Index].Nodes.Add(playerName, playerName);
tn.ImageIndex = 0; //player icon
}
else //division doesn't exist - add division, then add player
{
tn = this.tview_roster.Nodes.Add(division, division);
tn.ImageIndex = 1; //division icon
AddPlayerToTreeView(playerName, division);
}
}
And the result is this:
I'm not sure why it won't work.. and I'm at a loss. Any help would be appreciated.
Well, well... maybe something like the following.
Access the combo's data source, which is a DataTable, and extract selected row and column value using selected index. Maybe add some error handling, too.
private void btn_add_Click(object sender, EventArgs e)
{
var data = cmbo_divisions.DataSource as DataTable;
var row = data.Rows[cmbo_divisions.SelectedIndex];
var selected = row["title"].ToString();
AddPlayerToTreeView(txt_player_name.Text, selected);
}
Try this :
private void btn_add_Click(object sender, EventArgs e)
{
object selItem = cmbo_divisions.SelectedItem;
AddPlayerToTreeView(txt_player_name.Text, cmbo_divisions.SelectedItem as string);
}
ToString() will get the type name, but in that case the SelectedItem is a string.
Try with:
private void btn_add_Click(object sender, EventArgs e)
{
AddPlayerToTreeView(txt_player_name.Text, cmbo_divisions.Items[cmbo_divisions.SelectedIndex].Text);
}
EDIT: Updated to a better way

get repositoryItemGridLookupEdit parent's currentrow processed

I have a Gridview and a RepositoryItemGridLookUpEdit in that GridView
I want to show a CustomDisplayText in the RepositoryItemGridLookUpEdit
private void rgluePerson_CustomDisplayText(object sender, DevExpress.XtraEditors.Controls.CustomDisplayTextEventArgs e)
{
var person = rgluePerson.GetRowByKeyValue(e.Value) as Person;
var name = person.Name;
var surname = person.Surname;
e.DisplayText = name + ", " + surname;
}
}
The problem is that the person name depends of another cell in the same row (in the main Gridview), and i don't know how to get the current's Gridview row being processed (current row doesn't work since i need the row being processed in the moment)...... i can't use a gridView event cuz it will change the cell value, but i want to change the Text value.
Does anyone knows how to do that?
You cannot get the row being processed by the CustomDisplayText event because there are no such fields or properties that contains current row. You can only use this event for focused row. For this your must check if sender is type of GridLookUpEdit:
private void rgluePerson_CustomDisplayText(object sender, CustomDisplayTextEventArgs e)
{
if (!(sender is GridLookUpEdit))
return;
var anotherCellValue = gridView1.GetFocusedRowCellValue("AnotherCellFieldName");
//Your code here
e.DisplayText = yourDisplayText;
}
For not focused rows you can use only ColumnView.CustomColumnDisplayText event:
private void gridView1_CustomColumnDisplayText(object sender, CustomColumnDisplayTextEventArgs e)
{
if (e.Column.ColumnEdit != rgluePerson)
return;
var anotherCellValue = gridView1.GetListSourceRowCellValue(e.ListSourceRowIndex, "AnotherCellFieldName");
//Your code here
e.DisplayText = yourDisplayText;
}

Obtaining values from DevExpress GridControl

How to populate data into text fields whenever I click on the cell of the row?
For standard DataGridView I can use the following the code
void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
txtguard_id.Text = dataGridView1.SelectedRows[0].Cells["GuardId"].Value.ToString();
DateHired.Value = (DateTime)dataGridView1.SelectedRows[0].Cells["DateHired"].Value;
Firstname.Text = dataGridView1.SelectedRows[0].Cells["FirstName"].Value.ToString();
Middlename.Text = dataGridView1.SelectedRows[0].Cells["MiddleName"].Value.ToString();
Lastname.Text = dataGridView1.SelectedRows[0].Cells["LastName"].Value.ToString();
txtguard_street.Text = dataGridView1.SelectedRows[0].Cells["Street"].Value.ToString();
txtguard_brgy.Text = dataGridView1.SelectedRows[0].Cells["Barangay"].Value.ToString();
txtguard_procity.Text = dataGridView1.SelectedRows[0].Cells["ProvinceorCity"].Value.ToString();
txtguard_age.Text = dataGridView1.SelectedRows[0].Cells["Age"].Value.ToString();
txtguard_bday.Value= (DateTime)dataGridView1.SelectedRows[0].Cells["Birthdate"].Value;
txtguard_male.Checked = (bool)dataGridView1.SelectedRows[0].Cells["Gender"].Value;
txtguard_female.Checked = (bool)dataGridView1.SelectedRows[0].Cells["Gender"].Value;
}
But in GridControl i dont know how to do it...
With DevExpress XtraGrid you can use practically the same approach:
using DevExpress.XtraGrid.Views.Grid;
//...
gridView1.RowClick += gridView_RowClick;
//...
void gridView_RowClick(object sender, RowClickEventArgs e) {
object id = ((GridView)sender).GetRowCellValue(e.RowHandle, "ID");
testBoxId.Text = id.ToString();
//...
}
or
using DevExpress.XtraGrid.Views.Grid;
//...
gridView1.RowCellClick += gridView_RowCellClick;
//...
void gridView_RowCellClick(object sender, RowCellClickEventArgs e) {
object id = ((GridView)sender).GetRowCellValue(e.RowHandle, "ID");
testBoxId.Text = id.ToString();
//...
}
Related help article: Obtaining and Setting Cell Values
UPDATE:
Note that these events will not fire when clicking on a row cell, if data editing is enabled and the ColumnViewOptionsBehavior.EditorShowMode property is set to MouseDown.
You can dissable inplace editing for view using the GridView.OptionsBehavior.Editable property.

Disabling Combobox with Leave event is selecting text

I'm using the Leave event on Combobox to disable it and load some data but, after leaving and disabling, it selects the whole text in Combobox. I want to unselect the text.
Im using:
cmbNome.DropDownStyle = ComboBoxStyle.DropDown;
cmbNome.AutoCompleteMode = AutoCompleteMode.Suggest;
cmbNome.AutoCompleteSource = AutoCompleteSource.CustomSource;
if it helps...
the code:
private void cmbNome_Leave(object sender, EventArgs e)
{
cmbNome.Enabled = false;
CarregarDados();
CarregarTelefones();
}
Try setting data source before disabling combo box:
string[] data = new string[] {
"Absecon","Abstracta","Abundantia","Academia","Acadiau","Acamas",
"Ackerman","Ackley","Ackworth","Acomita","Aconcagua","Acton","Acushnet",
"Acworth","Ada","Ada","Adair","Adairs","Adair","Adak","Adalberta","Adamkrafft",
"Adams"
};
private void comboBox2_Leave(object sender, EventArgs e)
{
comboBox2.DataSource = data;
comboBox2.Enabled = false;
comboBox2.SelectedIndex = -1;
}
This code fills the combo with data; however, no item is selected and text field is empty
EDIT: added sample data
Try to first deselect item and than set combobox disabled.
cmbNome.SelectedIndex = -1;
cmbNome.Enabled = false;

Categories

Resources