DataGridView Row Click to Linq Object - c#

I'm a beginner with C# so I made a little app, to figure out how to work with Linq and databased in C#.
What I'm trying to do is in a DataGridView when someone clicks a row containing some data I want to go from e.RowIndex to a Linq object of the data in that row, my attempt involved using the DataBoundItem.
But for whatever reason the currentAd variable in this code always gives me a null value.
private void clickRow(object sender, DataGridViewCellEventArgs e)
{
richTextBox1.Text = "There is a clickRow event with row index " + e.RowIndex;
Ad currentAd = adsDataGridView.Rows[e.RowIndex].DataBoundItem as Ad;
if (currentAd != null) // The problem is it is always null
{
MessageBox.Show( currentAd.ToString() );
}
}
Thanks for your help.

In the examples given on the MSDN site, they cast the row to a DataGridViewRow object first, before taking the DataBoundItem, so you might want to try it this way:
private void clickRow(object sender, DataGridViewCellEventArgs e)
{
richTextBox1.Text = "There is a clickRow event with row index " + e.RowIndex;
DataGridViewRow row = adsDataGridView.Rows[e.RowIndex] as DataGridViewRow;
Ad currentAd = row.DataBoundItem as Ad;
if (currentAd != null)
{
MessageBox.Show( currentAd.ToString() );
}
}

Related

string values of selected row in datagridview by clicking ANYWHERE in that row

I am using the code below to retrieve values from the selected row it works... but has a glitch.... It will only retrieve the strings if you click on the actual text in any cell of that row.... if you click anywhere of white area in a cell of that row it will not execute .. Any ideas as to how to fix this glitch??
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
listBox1.ClearSelected();
OnlineNamebox.Text = "";
OnlinePasswordbox.Text = "";
OnlineEmailbox.Text = "";
OnlineShortcodebox.Text = "";
ListCombobox.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString();
OnlineNamebox.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString();
OnlineEmailbox.Text = dataGridView1.CurrentRow.Cells[2].Value.ToString();
OnlinePasswordbox.Text = dataGridView1.CurrentRow.Cells[3].Value.ToString();
OnlineShortcodebox.Text = dataGridView1.CurrentRow.Cells[5].Value.ToString();
}
I found a work around for obtaining the cell values based off of dash's answer on a kind of similar question using the cellmouseclick instead of cellclick
with the code below it dont matter where you click at in the row it executes the strings even if not directly clicking on the text in a cell
private void DatagridView1_CellMouseClick(Object sender, DataGridViewCellMouseEventArgs e)
{
ListCombobox.Text = this.dataGridView1.CurrentRow.Cells[0].Value.ToString();
OnlineNamebox.Text = dataGridView1.CurrentRow.Cells[1].FormattedValue.ToString();
OnlineEmailbox.Text = dataGridView1.CurrentRow.Cells[2].Value.ToString();
OnlinePasswordbox.Text = dataGridView1.CurrentRow.Cells[3].Value.ToString();
OnlineShortcodebox.Text = dataGridView1.CurrentRow.Cells[5].Value.ToString();
}
and I added the code below to the load event
dataGridView1.CellMouseClick += DatagridView1_CellMouseClick;
hope it helps anyone who runs into this particular problem or that is looking for the basics

need to tick the checkbox in Datagridview C#

I need to tick the checkbox in datagridview.in my case, I wanna do validation when the user going to untick the checkbox,
I wanna tick the checkbox after message will show
private void dgvBookingType_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
DataGridViewRow dgvRow = dgvBookingType.CurrentRow;
if (dgvRow.Cells[0].Value.ToString() == "True")
{
dgvRow.Cells[0].Value = true;
if (_dsEvent.Tables.Contains("PackageBookingType"))
{
if (_dsEvent.Tables["PackageBookingType"] != null)
{
DataRow[] selectedRow = _dsEvent.Tables["PackageBookingType"].Select("BookingTypeId=" + dgvRow.Cells[1].Value + " ");
if (selectedRow.Length > 0)
oUtilOptimised.ShowGenericUIValidation("There are packages that belong to the selected booking type added to the event. Remove the packages in order to disable the selected booking type", MessageBoxButtons.OK, MessageBoxDefaultButton.Button1, this, true);
}
}
}
}
please help me

How to move selected rows from one datagridview to another datagridview in c#?

I tried this code to move selected rows from datagridview2 to datagridview1.But when I clicked to add button to move selected rows from datagridview2. And it also added to datagridview 2.But an error occurred through exception which is "Object reference not set to an instance of an object".How to solve this. My code as follows
private void button1_Click(object sender, EventArgs e)
{
try
{
this.dataGridView1.Rows.Clear();
foreach (DataGridViewRow row in dataGridView2.Rows)
{
int n = dataGridView1.Rows.Add();
bool checkedCell = (bool)dataGridView2.Rows[n].Cells[0].Value;
if (checkedCell == true)
{
dataGridView1.Rows[n].Cells[0].Value = row.Cells[1].Value;
dataGridView1.Rows[n].Cells[1].Value = row.Cells[2].Value;
dataGridView1.Rows[n].Cells[3].Value = row.Cells[3].Value;
}
}
}
catch (Exception ex)
{
MessageBox.Show(" Error " + ex.Message);
}
}
I need to do this.But data should load by clicking load button
when you add row in datagridview2 you must set value of boolean column as same as :
dataGridView2.Rows.Add("1", "2", "3", false);
other solution for do that:
this.dataGridView1.Rows.Clear();
foreach (DataGridViewRow row in dataGridView2.SelectedRows.Cast<DataGridViewRow>().ToList())
{
this.dataGridView1.Rows.Add(row.Cells[0].Value, row.Cells[1].Value, row.Cells[2].Value);
}

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.

Why does the datagridview update, but the db does not?

I have been searching this answer for three days and so far no answer I found has worked. I am using a SQL db with a DataSet, Binding Source, Table Adapter, Table Adapter Manager, Binding Navigator and DataGridView. I am trying to use the fields on the left to update the db and just use the DataGridView as a view. The app updates from the textboxes to the DataGridView just fine but when I use the Update button to call:
this.Validate();
this.directoryBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.companyContactsDataSet1);
Nothing happens and the db stays the same. I do not know how to watch the variables in the Dataset, to see what their values are, so I have no clue if the DataSet is passing values into the UpdateAll function.
Here is the main code:
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'companyContactsDataSet1.Directory' table. You can move, or remove it, as needed.
this.directoryTableAdapter.Fill(this.companyContactsDataSet1.Directory);
lblTotalRows.Text = "Total number of records: " +directoryBindingSource.Count.ToString();
position = directoryBindingSource.Position + 1;
lblCurrentRow.Text = "Current Row: " + position.ToString();
}
private void bindingNavigator1_RefreshItems(object sender, EventArgs e)
{
//lblCurrentRowCopy.Text = "Current Row: "; //+ this.bindingNavigator1.CountItemFormat.ToString();
}
int position = 0;
private void btnPrevious_Click(object sender, EventArgs e)
{
directoryBindingSource.MovePrevious();
position = directoryBindingSource.Position + 1;
lblCurrentRow.Text = "Current Row: " + position.ToString();
}
private void btnNext_Click(object sender, EventArgs e)
{
directoryBindingSource.MoveNext();
position = directoryBindingSource.Position + 1;
lblCurrentRow.Text = "Current Row: " + position.ToString();
}
int count = 0;
private void btnAddRecord_Click(object sender, EventArgs e)
{
//This event handler moves to the last record and gets the value of the ID column.
//Then it parces that string value in the count variable. The position of the records
//is recorded and sent to the position label and a new row is added for the next record.
//The add.New function clears the fields and begins a new row. Then the count variable
//is incremented by one and cast to string to be placed into the idTextBox field.
//This was my solution to not having a way to use an autonumber field for ID. When I
//tried to use the SQL newID function in a table it was not allowed. I had many problems trying to use this line
//[Id] uniqueidentifier ROWGUIDCOL DEFAULT NEWID() not null IDENTITY ,
directoryBindingSource.MoveLast();
count = Int32.Parse(this.dataGridView1.CurrentCell.Value.ToString());
directoryBindingSource.AddNew(); // This throws an exception if the cursor is in any column but the ID column when caoo
count++;
idTextBox.Text = count.ToString();
position = directoryBindingSource.Position + 1;
lblCurrentRow.Text = "Current Row: " + position.ToString();
lblTotalRows.Text = "Total number of records: " + directoryBindingSource.Count.ToString();
}
private void btnUpdate_Click(object sender, EventArgs e)
{
//need to call binding source update method
try
{
//this.directoryTableAdapter.Insert(count, fNameTextBox.Text, lNameTextBox.Text, addressTextBox.Text, cityTextBox.Text,
//stateTextBox.Text, zipTextBox.Text, emailTextBox.Text, phoneTextBox.Text, deptTextBox.Text);
this.Validate();
this.directoryBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.companyContactsDataSet1);
//this.companyContactsDataSet1.AcceptChanges();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
That's all I can think of for now.

Categories