RowUniqueID in filtered row - c#

could somebody help me in C# programing in an web application. Namely, how can we find out RecordUniqueId of the filtered row....in order to further edit (i.e., set values in some other columns in the same row), based on RecordUniqueId value? Or, is it possible to, upon clicking on enter button in order to search for certain row, to immediately have some actions performed on the values in some other columns of filtered row? Let me say in other words, to have some kind of automation of editing values in some other columns of the filtered row?
Thanks in advance
public class PartyVuk2010GENTableControlRow : BasePartyVuk2010GENTableControlRow
{
}
public class PartyVuk2010GENTableControl : BasePartyVuk2010GENTableControl
{
public override void MarkDiscontinued_Click(object sender, ImageClickEventArgs args)
{
try {
DbUtils.StartTransaction();
foreach (PartyVuk2010GENTableControlRow rc in this.GetSelectedRecordControls()) {
PartyVuk2010GENRecord rec;
rec = PartyVuk2010GENTable.GetRecord(rc.RecordUniqueId, true);
if (rec != null) {
rec.Discontinued = true;
rec.Test = "10";
rec.BallotOrder = PartyVuk2010GENTable.Instance.GetLargest()+1;
rec.Save();
}
}
DbUtils.CommitTransaction();
}
catch (Exception ex) {
BaseClasses.Utils.MiscUtils.RegisterJScriptAlert(this, "BUTTON_CLICK_MESSAGE", ex.Message);
}
finally {
DbUtils.EndTransaction();
}
this.DataChanged = true;
}

Related

Toolstripmenuitem not running method C#

I have a method that foreaches a row within a datagridview and starts a process. However, when I click the toolstripmenuitem to execute the method it does not work. Any suggestions?
This is the toolstripmenuitem ^
private void sIGNATUREToolStripMenuItem_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
if (Properties.Settings.Default.ManageContactsView == "STACKED")
{
ViewSignature(AllContacts);
}
else if (Properties.Settings.Default.ManageContactsView == "LISTED")
{
ViewSignature(AllContactsLISTED);
}
else
{
ViewSignature(AllContactsFULL);
}
}
This is the code that is placed in the menu items click property ^
void ViewSignature(DataGridView AllContacts)
{
foreach (DataGridViewRow row1 in AllContacts.Rows)
{
try
{
if (Convert.ToBoolean(row1.Cells[18].Value))
{
Process.Start(Properties.Settings.Default.ReferencePoint + #"/Contacts/Contact_" + row1.Cells[0].Value.ToString() + #"/Signature.jpg");
}
}
catch
{
//Error message if the system cannot remove the contact from the database.
MessageBox.Show("Sorry, something went wrong. Please try again later.\n\nERROR CODE: BINSPIRE1009", "BLUEBERRY INSPIRE 2022", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
This is the method I am trying to execute which fetches a column and row value from the datagridview and starts a process.

DataGridView not loading data programmatically

I am working on a Windows application where I get an input from a TextBox and add it to the DataGridView when user clicks on a Button (Add).
My problem is that when I add the text for the first time, it works fine and its added to the grid.
When I add new text, it's not added to the DataGridView. Once the Form is closed and reopened with the same object then I am able to see it.
Code:
private void btnAddInput_Click(object sender, EventArgs e)
{
if (Data == null)
Data = new List<Inputs>();
if (!string.IsNullOrWhiteSpace(txtInput.Text))
{
Data.Insert(Data.Count, new Inputs()
{
Name = txtInput.Text,
Value = string.Empty
});
}
else
{
MessageBox.Show("Please enter parameter value", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
txtInput.Text = "";
gridViewInputs.DataSource = Data;
}
I am not sure what is causing the record not to be added to grid on second add button click.
You could set the DataGridView.DataSource to null before setting a new one.
This would cause the DataGridView to refresh its content with the new data in the source List<Inputs>:
the underlying DataGridViewDataConnection is reset only when the DataSource reference is different from the current or is set to null.
Note that when you reset the DataSource, the RowsRemoved event is raised multiple times (once for each row removed).
I suggest to change the List to a BindingList, because any change to the List will be reflected automatically and because it will allow to remove rows from the DataGridView if/when required: using a List<T> as DataSource will not allow to remove a row.
BindingList<Inputs> InputData = new BindingList<Inputs>();
You can always set the AllowUserToDeleteRows and AllowUserToAddRows properties to false if you don't want your Users to tamper with the grid content.
For example:
public class Inputs
{
public string Name { get; set; }
public string Value { get; set; }
}
internal BindingList<Inputs> InputData = new BindingList<Inputs>();
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = InputData;
}
private void btnAddInput_Click(object sender, EventArgs e)
{
string textValue = txtInput.Text.Trim();
if (!string.IsNullOrEmpty(textValue))
{
InputData.Add(new Inputs() {
Name = textValue,
Value = "[Whatever this is]"
});
txtInput.Text = "";
}
else
{
MessageBox.Show("Not a valid value");
}
}
If you want to keep using a List<T>, add the code required to reset the DataGridView.DataSource:
private void btnAddInput_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textValue))
{
//(...)
dataGridView1.DataSource = null;
dataGridView1.DataSource = InputData;
txtInput.Text = "";
}
//(...)

Search in DataGridView giving error

I'm trying to search employees by Name.
Of course, there can be same Names for different employees.
I want my function to highlight all the employees with the Name i entered.
If i use break; i will get only the first value found, if I don't use break; I get all values but I also get the Error: Object reference not set to an instance of object.
Here is the full code:
// SAMEKLET DARBINIEKU
private void btn_mekletDarbinieku_Click(object sender, EventArgs e)
{
string searchValue = txt_mekletDarbinieku.Text;
DGV_darbinieks.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
try
{
foreach (DataGridViewRow row in DGV_darbinieks.Rows)
{
if (row.Cells[1].Value.ToString().Equals(searchValue))
{
row.Selected = true;
//break; // šito varētu izmantot personas kodam, jo tāds tik viens būtu
}
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}

How to rebind datasource to a winform DataGridView Combobox column?

I have a DataGridView in winform with 2 combo box columns: 1) Companies, 2) Accounts.
I want to update the accounts combo box according to the selected company.
I have this code:
void recipientsDataGrid_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
try
{
ComboBox cb = e.Control as ComboBox;
if (cb != null)
{
cb.SelectedValueChanged -= new EventHandler(companyCombobox_SelectedValueChanged);
cb.SelectedValueChanged += new EventHandler(companyCombobox_SelectedValueChanged);
}
}
catch (Exception ex)
{
}
}
private void companyCombobox_SelectedValueChanged(object sender, EventArgs e)
{
try
{
var currentCell = recipientsDataGrid.CurrentCellAddress;
if (currentCell.X == 3)
{
var sendingCB = sender as DataGridViewComboBoxEditingControl;
int companyId = sendingCB.SelectedValue.ToInt();
DataTable dtAccounts = m_CustomersFunctions.GetCompanyAccounts(companyId);
DataGridViewComboBoxCell cboAccounts = (DataGridViewComboBoxCell)recipientsDataGrid.Rows[currentCell.Y].Cells["Account"];
cboAccounts.ValueMember = "account_id";
cboAccounts.DisplayMember = "AccountName";
cboAccounts.DataSource = dtAccounts;
int defaultAccountId = (from row in dtAccounts.AsEnumerable()
where row.Field<string>("AccountName").EndsWith("*")
select row.Field<int>("account_id")).FirstOrDefault();
if (defaultAccountId > 0)
cboAccounts.Value = defaultAccountId;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
It works fine in the first time I select a company, but when I change the company and try to update the data source for the accounts combo box I'm getting an error:
I tried to add the items manualy and not with a DataSource, and I got the same error.
How can I fix it ?
please...
Try to clear the value of accounts cell before rebind it, like this:
private void companyCombobox_SelectedValueChanged(object sender, EventArgs e)
{
try
{
var currentCell = recipientsDataGrid.CurrentCellAddress;
if (currentCell.X == 3)
{
var sendingCB = sender as DataGridViewComboBoxEditingControl;
int companyId = sendingCB.SelectedValue.ToInt();
DataTable dtAccounts = m_CustomersFunctions.GetCompanyAccounts(companyId);
DataGridViewComboBoxCell cboAccounts = (DataGridViewComboBoxCell)recipientsDataGrid.Rows[currentCell.Y].Cells["Account"];
cboAccounts.Value = null; //Add this code
cboAccounts.ValueMember = "account_id";
cboAccounts.DisplayMember = "AccountName";
cboAccounts.DataSource = dtAccounts;
int defaultAccountId = (from row in dtAccounts.AsEnumerable()
where row.Field<string>("AccountName").EndsWith("*")
select row.Field<int>("account_id")).FirstOrDefault();
if (defaultAccountId > 0)
cboAccounts.Value = defaultAccountId;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I had the same problem in vb.net .
Not sure if my solution is good, but it works for me.
Briefly: I create a new temporary "DataGridViewComboBoxCell" object, I assign the "DataSource" and the "Value" (which must belong to "DataSource" !!! otherwise the error "value is not valid" comes out) and assign the new object to correct cell in my "DataGridView" main object, like this:
Dim oDataGridViewComboBox As New DataGridViewComboBox With {
.DataSource = MyDataSource
.Value = MyCorrectValueContainedInDataSource
}
oMyDataGridView.Rows(iLineOfComboBox).Cells("ComboBoxColumnName") = oDataGridViewComboBox
The error "value is not valid" is thrown because the ComboBox value is not included among those present in "DataSource".
P.S.: Sorry, I don't know C# ... but the problem is the same, and I have found this post during a search of solution.

Entity Framework - Casting the retrieved Combobox value to string

Using Entity Framework, I have a Combobox showing a list of data retrieved from a database.
using System; //I removed the other using statements here to preserve space
namespace ExTea_BackEnd
{
public partial class frmAddBreakdown : Form
{
ExTeaEntities Breakdowns;
Breakdown_Type BreakdownTypes;
public frmAddBreakdown()
{
InitializeComponent();
}
private void cmbBreakdownType_SelectedIndexChanged(object sender, EventArgs e)
{
Breakdown_Type breakdownType = (Breakdown_Type)cmbBreakdownType.SelectedItem;
string selectedBreakdownTypeId = breakdownType.BrkdwnId;
IQueryable<Breakdown_Type> breakdownTypeQuery = from t in Breakdowns.Breakdown_Types
where t.BrkdwnId == selectedBreakdownTypeId
select t;
List<Breakdown_Type> selectedBreakdownId = breakdownTypeQuery.ToList();
if (selectedBreakdownId != null && selectedBreakdownId.Count > 0)
{
BreakdownTypes = selectedBreakdownId.First();
txtBreakdownId.Text = BreakdownTypes.BrkdwnId.ToString();
}
else
{
BreakdownTypes = null;
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
Breakdown newBreakdown = new Breakdown();
Breakdown_Type breakdownType = (Breakdown_Type)cmbBreakdownType.SelectedItem;
newBreakdown.BrkdwnType = breakdownType.ToString(); //this is where the error occurs
newBreakdown.MachineId = txtMachineId.Text.Trim();
newBreakdown.MachineType = txtMachineType.Text.Trim();
newBreakdown.ReportedDate = dtpDate.Value;
newBreakdown.JobStatus = "I";
Breakdowns.AddToBreakdowns(newBreakdown);
int rowsAffected = Breakdowns.SaveChanges();
if (rowsAffected > 0)
{
MessageBox.Show(rowsAffected + " records added!", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show("Error occured! " + ex.Message);
}
}
}
}
I'm trying to save the data in the form back to the database, an error occurs when trying to cast the value selected from the Combobox. Even when I've casted it to the right type, it does not save the selected value! But this,
I'm clueless on what I'm doing wrong here? Can anyone please tell me how to correct this?
Thank you.
newBreakdown.BrkdwnType = breakdownType.ToString();
Here you are just calling .ToString() Method of your object, so it is returning the Type Name, which you are able to view in database table record, for getting the BrkDwnType Property value you should change statement to
newBreakdown.BrkdwnType = breakdownType.BrkdwnType;
it should just be:
newBreakdown.BrkdwnType = cmbBreakdownType.SelectedItem.ToString();
no need for casting selectedItem if you just want the string value. From a design point of view, you should probably normalize your database and use an ID for breakDownType that references another table with BreakDown types.

Categories