System.Data.DataRowView in CombocBox C# - c#

I am working on a Windows forms application. I have two combo boxes, one to select the profile and the other to select the type of matrix. Each profile has a number of matrices which needs to be displayed in the combo box and set to the first matrix as default when the form loads.
I have set the data source and assigned the DisplayMember and Value member properties to both the combo boxes. However, when the form loads, in the second combo box where the different types of matrices should be listed, I have only System.Data.DataRowView for all the values. However, when I select the profile from the first comboBox, the second box is refreshed and the values are displayed correctly.
The code for the Profile comboBox
ddProfile.DataSource = dtProfile;
ddProfile.ValueMember = "ID";
ddProfile.DisplayMember = "Description";
ddProfile.Enabled = dtProfile.Rows.Count > 1;
foreach (DataRow dr in dtProfile.Rows)
{
if (dr["Ordinal"].ToString() == "1")
{
ddProfile.SelectedValue = dr["ID"];
break;
}
}
Code for the matrix comboBox
DataTable dtMatrix = new DataTable();
dtMatrix = DBConnector.GetTable("RiskMatrixList", "*", "", $"Profile={ddProfile.SelectedValue}", DBConnector.ConnectionType.Templates);
dtMatrix = DBConnector.GetTable($"SELECT * FROM RiskMatrixList WHERE Profile={ddProfile.SelectedValue}");
ddRiskMatrix.DataSource = dtMatrix;
ddRiskMatrix.DisplayMember = "Description";
ddRiskMatrix.ValueMember = "ID";
ddRiskMatrix.Enabled = dtMatrix.Rows.Count > 1;
foreach (DataRow dr in dtMatrix.Rows)
{
if (dr["IsDefault"].ToString() == "1")
{
ddRiskMatrix.SelectedValue = dr["ID"].ToString();
break;
}
}
Why am I not getting the right values when the form loads?

I observed that combo_SelectedValueChanged is called twice, when ValueMember and DisplayMember are being assigned, and then - I had the same problem.
After one day of very productive work :/ I discovered the trick:
1/ Added flag to form's properties:
public partial class frmMain : Form
{
bool IsLoadingCombo = false;
2/ Simply modified combo_SelectedValueChanged:
private void cbFilter_SelectedValueChanged(object sender, EventArgs e)
{
if (isLoadingCombo)
return;
// rest of method's code
}
Not very elegant, but better than wasting the next few days.
I think, that problem is that "rest of method's code" needs selected value which is unknown, when the method is stupidly triggered when disp/value members are being asigned.

Related

How to get a ComboBox in a DataGridViewCell to drop down after a single click?

I have a DataGridView which has it's first column's style set to a ComboBox rather than the default TextBox. Since the number of rows in the DataGridView is not fixed on startup I cannot load in data to the ComboBoxes for each row when a new row is added. So I tried loading on the event of a user adding a row to the DataGridView:
public void myDataGridView_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
// Identifiers used are:
var myTableAdapter = new databaseTableAdapters.myTableTableAdapter();
var myDataTable = myTableAdapter.GetData();
int rowIndex = myDataGridView.CurrentcellAddress.Y;
var comboBoxCell = (DataGridViewComboBoxCell)myDataGridView.Rows[rowIndex].Cells[0];
string itemToAdd;
// Load in the data from the data table
foreach (System.Data.DataRow row in myDataTable.Rows)
{
// Get the current item to be added
itemToAdd = row[0].ToString();
// Make sure there are no duplicates
if (!comboBoxCell.Items.Contains(itemToAdd))
{
comboBoxCell.Items.Add(itemToAdd)
}
}
}
but this only will allow the user to see the drop down options after a second click. I would like to be able to have the user only click on the combo box once and see the options rather than the less intuitive double click. How can this be done?
The cell must gain focus for the drop down to occur, so the double click is actually a single click to gain focus on that cell and the second click is what causes the drop down to occur. So to see how to change focus following this link. I was able to modify the code with a single line of code
public void myDataGridView_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
// Identifiers used are:
var myTableAdapter = new databaseTableAdapters.myTableTableAdapter();
var myDataTable = myTableAdapter.GetData();
int rowIndex = myDataGridView.CurrentcellAddress.Y;
var comboBoxCell = (DataGridViewComboBoxCell)myDataGridView.Rows[rowIndex].Cells[0];
string itemToAdd;
// Load in the data from the data table
foreach (System.Data.DataRow row in myDataTable.Rows)
{
// Get the current item to be added
itemToAdd = row[0].ToString();
// Make sure there are no duplicates
if (!comboBoxCell.Items.Contains(itemToAdd))
{
comboBoxCell.Items.Add(itemToAdd)
}
}
// Send the focus to the next combo box (removes need for a double click)
myDataGridView.CurrentCell = myDataGridView.Rows[rowIndex + 1].Cells[0]; // <--- HERE
}

Pushing values from DataView built on one Windows Form to another Windows Form

I have 2 windows forms. One form with datagridview and button, and the other form with labels. More or less like Master-Detail design. I have 2 related tables in database. I can fill the datagridview nicely with data from the main table. First I select data on datagridview, and I want to use the button to display the values on the labels located on another form.
Once data is loaded on datagridview; I use the following code for the methods to filter the underlying tables based on selection made from datagridview:
[form 2]
public DataView EnterpriseView()
{
foreach (DataGridViewRow row in Viewer.SelectedRows)
identifier = row.Cells["BusinessName"].Value.ToString();
var EnterpriseVw = new DataView(EnterpriseDT)
{
RowFilter = "BusinessName = '" + identifier + "'"
};
return EnterpriseVw;
}
After returning the view, I want to use the button to push the information to another form that has the labels. I'm not sure about how to get this working. I tried different codes of my own, and it doesn't work
My issue how to code the button_click event. And is there another event I need to call for this to work? How does the button know if I have selected something on the datagridview? How does the datagridview know I have clicked the button? I tied something like this for the button:
[form 2]
private void button1_Click(object sender, EventArgs e)
{
index = Viewer.SelectedRows[0].Index;
Viewer.Rows[index].Selected = true;
//EnterpriseView();
//DetailsView();
//this.Click += new EventHandler(Viewer_SelectionChanged);
if (Viewer.Rows[index].Selected == true)
{
var frm1 = new form1(); //form with labels
//foreach(DataGridViewRow row in Viewer.SelectedRows)
frm1.Publish(); //method that assigns data to labels
}
It doesn't work
I tried using somthing like this for the labels:
[form 1]
public void Publish()
{
var frm2 = new form2();
var vEnterprise = frm2.EnterpriseView();
Email.DataBindings.Add("Text", vEnterprise, "EmailAddress");
}
To Get values from Selected Row of the DataGridView you need to change some properties :
First You need to set SelectionMode to FullRowSelect.
Second You need to set MultiSelect to False.
You can do it through the properties tab.
Then we can use dataGridView1.SelectedRows it will return DataGridViewSelectedRowCollection a list of the selected rows, but since we disabled multiSelect there will always be just one so we can use [0].
Now in the Button_click event Handler
private void button1_Click(object sender, EventArgs e)
{
// To Get The Selected Row
var dr = dataGridView1.SelectedRows[0];
// The Cells Property is going to return DataGridViewCellCollection a list again
// Basically the columns so the first one will be the first column and so on
string item1 = dr.Cells[0].Value.ToString();
string item2 = dr.Cells[1].Value.ToString();
string item3 = dr.Cells[2].Value.ToString();
}
In the Form with the labels Define a second constructor.
Say we Have 3 Labels
We gonna define a second constructor that takes 3 Strings, Like this
public TheSecondForm(String S1, String S2,String S3)
{
label1.Text = S1;
label2.Text = S2;
label3.Text = S3;
}
Then The button Event Handle will become like this :
private void button1_Click(object sender, EventArgs e)
{
var dr = dataGridView1.SelectedRows[0];
string item1 = dr.Cells[0].Value.ToString();
string item2 = dr.Cells[1].Value.ToString();
string item3 = dr.Cells[2].Value.ToString();
// What was added
TheSecondForm frm2 = new TheSecondForm(item1, item2, item3);
frm2.Show();
}
By Now the labels will be populated.

how to get value of selected row in DropDown and Grid view

i have 2 question...
1. i have a gridview that bind some data form database that way
DataSource = Company.GetAllCompany();
dgvCompanys.AutoGenerateColumns = false;
dgvCompanys.DataSource = _DataSource;
dgvcolNameEn.DataPropertyName = "MyEnglishName";
dgvcolAddress.DataPropertyName = "MyAddress";
dgvcolCode.DataPropertyName = "MyCode";
dgvcolKeyId.DataPropertyName = "MyKeyId";
it's worked now i want get the KeyId of selected row
private void dgvCompanys_SelectionChanged(object sender, EventArgs e)
{
if (dgvCompanys.SelectedRows.Count > 0)
{
mtxtCode.Text=dgvCompanys.SelectedRows[0].Cells[1].Value.ToString();
}
}
this code have this error Object reference not set to an instance of an object.
what i have to do for this?
question 2.i have textboxdropdownlist(devComponent)
and sourced that way:
List<Company> _DataCompany;
_DataCompany = Company.GetAllCompany();
cmbCompany.DisplayMember = "MyEnglishName";
cmbCompany.DataSource = _DataCompany;
that worked correctly but i want get KeyId of rows selected in dropdown now what i have to do?
Question 1 : perhaps your dataset have only one column, so the right code is :
dgvCompanys.SelectedRows[0].Cells[0].Value.ToString();
Question 2 is not clear for me, but you can access to the selected item with :
DropDown.SelectedItem.ToString()

DataGridView not showing contents of custom column on initial draw

I have a dataGridView that binds to a list of "kit" objects as a datasource. I have written a method AddLocalizedStringColumn() that adds a new
column to the datagrid ("Localized String"), and populates it by reading data from another column ("stringCode"). If the column exists already,
it just updates the values of the column. I have placed this method inside an event based on when the datagrid's datasource changes.
The debugger confirms that all cell values are being assigned properly, including Cell.FormattedValue. However, when viewing the grid for the
first time, the column is blank! Even after running it twice during the first load, the Localized String column remains blank. If I run the
AddLocalizedStringColumn method a second time after the initial draw, whether by button or by event, it shows the values correctly.
I'm not sure why this is happening. I can only imagine it has something to do with the dataGrid's initial draw.
While the actual code is proprietary, here is a similar example.
public static void AddLocalizedStringField(this DataGridView gridView, string localeStringIDProperty, string columnTitle, int valueIndex)
{
if (string.IsNullOrEmpty(localeStringIDProperty)) return;
if (string.IsNullOrEmpty(columnTitle)) return;
if (valueIndex < 0 || valueIndex >= gridView.Columns.Count) return;
if (gridView.Columns.Contains(localeStringIDProperty) == false) return;
if (gridView.Columns.Contains(columnTitle))
{
valueIndex = gridView.Columns.IndexOf(gridView.Columns[columnTitle]);
}
else
{
DataGridViewColumn newColumn = new DataGridViewColumn();
newColumn.Name = columnTitle;
newColumn.CellTemplate = new DataGridViewTextBoxCell();
gridView.Columns.Insert(valueIndex, newColumn);
}
int idIndex = gridView.Columns.IndexOf(gridView.Columns[localeStringIDProperty]);
foreach(DataGridViewRow row in gridView.Rows)
{
DataGridViewCell foundCell = row.Cells[columnTitle];
foundCell.Value = "English Text";
gridView.InvalidateCell(foundCell);
}
}
DataGridView dataGridViewStores = new DataGridView();
List<Store> _listOfStores = new List<Store>();
public void SetupForm() // Runs as part of the constructor
{
/* _listOfStores is filled with entries.*/
dataGridViewStores.DataSource = _listOfStores;
dataGridViewStores.AddLocalizedStringField("storeName", "translated name", 2);
// The column appears but is blank. The debugger shows all its cells have the correct contents.
}
public void RefreshColumn()
{
// Running this after the form is displayed shows the localized values correctly.
dataGridViewStores.AddLocalizedStringField("storeName", "translated name", 2);
}

All rows selected on clicked

I'm building a application in C# Winforms and using a Datagridview.
My problem is that when I click on a row, all rows are selected (without intention) and the application crashes (as the values inserted from the grid view selected row into labels are not intact (too many values...).
The correct behavior I'm looking for is the selection of on row only.
I thought the problem might be in the selectionMode (I used the value "RowHeaderSelect"), but I changed it, and the problem persisted, so it isn't it.
Do you have an idea what might be the problem ??
Not relying on much code, really, but here it is:
private void dgvCustomersList_MouseClick(object sender, MouseEventArgs e)
{
{
customerFunctions ChoosenRow = new customerFunctions(); //empty
DataGridViewRow dr = dgvCustomersList.SelectedRows[0];
ChoosenRow.CfirstName = dr.Cells[1].Value.ToString();
ChoosenRow.ClastName = dr.Cells[2].Value.ToString();
ChoosenRow.Caddress = dr.Cells[3].Value.ToString();
ChoosenRow.CcreditNumber = int.Parse(dr.Cells[7].Value.ToString());
ChoosenRow.CpersonalID = int.Parse(dr.Cells[5].Value.ToString());
}
}

Categories