How to copy selected row gridView to another Dexexpress? - winforms

I want to copy selected row in gridView1/gridControl1 to gridView2/gridControl2, gridView1 with DataSource and DataTable:
private void chon2_Click(object sender, EventArgs e)
{
for (int i = 0; i < gridView1.GetSelectedRows().Length; i++)
{
gridView2.AddNewRow();
gridView2.SetRowCellValue(i, "column2",gridView1.GetRowCellValue(i, "colum1").ToString());
}
}
But it does not work

Related

saving data at the Database SQLSERVER

I have a problem when I want to save the data in the database.
the exception is:
System.InvalidOperationException: 'DataColumn' Name_Faculty 'missing in DataTable' disconnGrid 'for SourceColumn' Name_Faculty '.'
public void fillGrid()
{
if (adoF2.ds.Tables["disconnGrid"] != null)
{
adoF2.ds.Tables["disconnGrid"].Clear(); // to get new update.
}
adoF2.da = new SqlDataAdapter("SELECT * FROM Students", adoF2.con1);
adoF2.da.Fill(adoF2.ds, "disconnGrid");
dataGridView1.DataSource = adoF2.ds.Tables["disconnGrid"];
}
public void fillCombo()
{
adoF2.da = new SqlDataAdapter("SELECT * FROM Faculty", adoF2.con1);
adoF2.da.Fill(adoF2.ds, "disconnCombo");
comboBox1.DataSource = adoF2.ds.Tables["disconnCombo"];
comboBox1.DisplayMember = adoF2.ds.Tables["disconnCombo"].Columns[1].ColumnName;
comboBox1.ValueMember = adoF2.ds.Tables["disconnCombo"].Columns[0].ColumnName; /* this column is a foreign key into 'Students' table*/
}
private void gestionStagiaire2_Load(object sender, EventArgs e)
{
fillGrid();
fillCombo();
}
// to add the new row in the dataTable[disconnGrid]
private void button1_Click(object sender, EventArgs e)
{
adoF2.row1 = adoF2.ds.Tables["disconnGrid"].NewRow();
adoF2.row1[0] = textID.Text;
adoF2.row1[1] = textName.Text;
adoF2.row1[2] = comboBox1.SelectedValue; // to get the value not what is diplayed on the UI of comboBox1.
for (int i = 0; i < adoF2.ds.Tables["disconnGrid"].Rows.Count; i++)
{
if (textID.Text == adoF2.ds.Tables["disconnGrid"].Rows[i].ToString())
{
MessageBox.Show("Sorry the students is existed", "Warning", MessageBoxButtons.OK);
return; // to avoid errors.
}
}
adoF2.ds.Tables["disconnGrid"].Rows.Add(adoF2.row1);
MessageBox.Show("The students has been added successfully", "info", MessageBoxButtons.OK,MessageBoxIcon.Information);
dataGridView1.DataSource = adoF2.ds.Tables["disconnGrid"]; // to get the newly update.
}
// to save the data into the database:
private void saveB_Click(object sender, EventArgs e)
{
adoF2.cmdbuilder = new SqlCommandBuilder(adoF2.da);
adoF2.da.Update(adoF2.ds.Tables["disconnGrid"]);
MessageBox.Show("Saving has been succeeded", "Info", MessageBoxButtons.OK);
}
try this code :
adoF2.cmdbuilder = new SqlCommandBuilder(adoF2.da);
adoF2.da.Update(adoF2.ds,"disconnGrid");
MessageBox.Show("Saving has been succeeded", "Info", MessageBoxButtons.OK);

Deleting from a Data Grid View

I have created a windows form application. I want this application to be able to use Linq to SQL to search for a record, and then for that record to be selected from a data grid view and deleted.
The form contains a textbox to enter the parameter, a search button and a delete button and a datagrid.
I have the search part working correctly and the data grid is populated but don't know how to implement clicking on the record in the data grid and deleting it.
Update - I have solved the solution. Changes have only been made to the btn_Delete_Click event handler so I have included the updated code for his button after the main code.
namespace DeleteForm
{
public partial class Form1 : Form
{
LinqtoStudentDataContext linqStud = new LinqtoStudentDataContext();
public Form1()
{
InitializeComponent();
}
private void btnDelete_Click(object sender, EventArgs e)
{
}
private void btnSearch_Click(object sender, EventArgs e)
{
var lastName = from stud in linqStud.Students
where txtFind.Text == stud.LastName
select stud;
dataGridView1.DataSource = lastName;
}
}
}
Updated code -
private void btnDelete_Click(object sender, EventArgs e)
{
if (this.dataGridView1.SelectedRows.Count > 0)
{
dataGridView1.Rows.RemoveAt(this.dataGridView1.SelectedRows[0].Index);
//linqStud.Students.DeleteAllOnSubmit();
linqStud.SubmitChanges();
}
}
First, set selection mode of DataGridView to FullRowSelect. Next, when assigning DataSource you should call ToList() - you can't use query as data source:
private void btnSearch_Click(object sender, EventArgs e)
{
var lastName = txtFind.Text;
var students = from stud in linqStud.Students
where stud.LastName == lastName
select stud;
dataGridView1.DataSource = students.ToList();
}
Get selected rows, and remove databound items (students) from context:
private void btnDelete_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
var student = row.DataBoundItem as Student;
linqStud.Students.Remove(student);
linqStud.SaveChanges();
}
}

changing datagridview selection color dynamically c#

the problem is that when i change the color of selected row by RowTemplate.DefaultCellStyle.SelectionBackColor in my form constructor it works but it does not work in button events when user clicks some button for changing grid selected back color!
any help please!
public Form1()
{
InitializeComponent();
dataGridView1.RowTemplate.DefaultCellStyle.SelectionBackColor=Color.Red; //this works fine
}
void button2_Click(object sender, EventArgs e)
{
dataGridView1.RowTemplate.DefaultCellStyle.SelectionBackColor=Color.Blue;//but this does not work
}
Try this ..
void dataGridView1_RowPrePaint(object sender,
DataGridViewRowPrePaintEventArgs e)
{
If (DatagridView1.Rows(DataGridView1.CurrentCell.RowIndex).Selected )
{
DataGridView1.Rows(DataGridView1.CurrentCell.RowIndex).DefaultCellStyle.SelectionBackColor=Color.Blue;
}
}
void button2_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
row.DefaultCellStyle.SelectionBackColor = Color.Blue
}
}
Update :
void button2_Click(object sender, EventArgs e)
{
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
col.DefaultCellStyle.BackColor = Color.Blue
}
}

refresh datagrid items without losing selected row - XAML

I have two datagrid's ( Master/detaiL). I refresh my window using DispatcherTimer for every 5 secs. when I select any row on my Master grid, the focus on the selected row stays only for those 5 secs, after that the selection focus moves to the top most row.
how to overcome this issue in XAML?
EDIT
public partial class MyWindow : Window
{
ProdEntities _prodEntities = new ProdEntities();
public MyWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
try
{
RebindData();
SetTimer();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void SetTimer()
{
DispatcherTimer dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 5);
dispatcherTimer.Start();
}
protected void dispatcherTimer_Tick(object sender, EventArgs e)
{
RebindData();
}
private void RebindData()
{
CollectionViewSource serversViewSource = (CollectionViewSource)(FindResource("serversViewSource"));
IQueryable<Server> serversQuery = this.GetServersQuery(_prodEntities );
serversViewSource.Source = serversQuery.ToList();
//serversViewSource.View.Refresh();
}
private IQueryable<Server> GetServersQuery(ProdEntities _prodEntities)
{
var serversQuery = _prodEntities.Servers.Where(c => c.Components.Any());
return serversQuery;
}
private void SaveChanges_Click(object sender, RoutedEventArgs e)
{
_prodEntities.SaveChanges();
}
}
XAML
<DataGrid AutoGenerateColumns="False" Foreground="DarkBlue" DataContext="StaticResource serversComponentsViewSource}"
ItemsSource="{Binding}" Name="componentsDataGrid">
Hi you need to preserve SelectedItem of your DataGrid before you call
serversViewSource.Source = serversQuery.ToList();
and then assign it back to SelectedItem of that DataGrid. But you will have to find the item in Collection that has same Values as that in preserved SelectedItem before you assign that object back to SelectedItem.
private void RebindData()
{
CollectionViewSource serversViewSource = (CollectionViewSource)(FindResource("serversViewSource"));
var selectedItem = (Server)componentsDataGrid.SelectedItem;
IQueryable<Server> serversQuery = this.GetServersQuery(_prodEntities);
serversViewSource.Source = serversQuery.ToList();
foreach (var item in (IEnumerable<Server>)serversViewSource.Source )
{
if (selectedItem.PropName == item.PropName)//Compare the values here
{
componentsDataGrid.SelectedItem = item;
break;
}
}
//serversViewSource.View.Refresh();
}

DataGrid select last cell programmatically

When the DataGrid below gets the focus for the first time and only the first time (ie, after some other control has had the focus), the last row, 2nd column should be focused and in edit.
I added a handler for the DataGrid.GotFocus, but it's complicated code and not getting the result above.
Anyone got an elegant, bullet proof solution?
I made tiny modifications to the code
the sender should always be the grid I want, so I just used that instead of relying on a name
When the SelectionUnit is FullRow, as my grid was before I changed it to CellOrRowHeader you
apparently can't call SelectedCells.Clear()
Code below:
private void OnDataGridKeyboardGotFocus(object sender, KeyboardFocusChangedEventArgs e)
{
var dg = sender as DataGrid;
if (_hasHadInitialFocus) return;
var rowIndex = dg.Items.Count - 2;
if (rowIndex >= 0 && dg.Columns.Count - 1 >= 0)
{
var column = dg.Columns[dg.Columns.Count - 1];
var item = dg.Items[rowIndex];
var dataGridCellInfo = new DataGridCellInfo(item, column);
if (dg.SelectionUnit != DataGridSelectionUnit.FullRow) {
dg.SelectedCells.Clear();
dg.SelectedCells.Add(dataGridCellInfo);
}
else {
var row = dg.GetRow(rowIndex);
row.IsSelected = true;
}
dg.CurrentCell = dataGridCellInfo;
dg.BeginEdit();
}
_hasHadInitialFocus = true;
}
New Question
I want to repeat the selection when the focus goes to another control in the window and then back to the grid.
I thought I could turn that _hasHadInitialFocus latch to false in a LostFocus event, but the code below is firing on cell changes.
Do you know how I should be trapping the lost focus event better, and do you agree that is the place to turn the latch off?
private void DataGridLostFocus(object sender, RoutedEventArgs e) {
_hasHadInitialFocus = false;
}
You may have to fiddle with the offsets depending on whether there's an new item row visible or not, but this works for me.
private bool _hasHadInitialFocus;
private void DataGridGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
if (!_hasHadInitialFocus)
{
if (dataGrid.Items.Count - 2 >= 0 && dataGrid.Columns.Count - 1 >= 0)
{
var dataGridCellInfo = new DataGridCellInfo(
dataGrid.Items[dataGrid.Items.Count - 2], dataGrid.Columns[dataGrid.Columns.Count - 1]);
dataGrid.SelectedCells.Clear();
dataGrid.SelectedCells.Add(dataGridCellInfo);
dataGrid.CurrentCell = dataGridCellInfo;
dataGrid.BeginEdit();
}
_hasHadInitialFocus = true;
}
}
I noticed that clicking into the grid leaves one cell selected and the target cell in edit mode. A solution to this if required is:
private void DataGridGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
EditCell();
}
private void PreviewMouseLBDown(object sender, MouseButtonEventArgs e)
{
if (!_hasHadInitialFocus)
{
e.Handled = true;
EditCell();
}
}
private void EditCell()
{
if (!_hasHadInitialFocus)
{
if (dataGrid.Items.Count - 2 >= 0 && dataGrid.Columns.Count - 1 >= 0)
{
var dataGridCellInfo = new DataGridCellInfo(
dataGrid.Items[dataGrid.Items.Count - 2], dataGrid.Columns[dataGrid.Columns.Count - 1]);
dataGrid.SelectedCells.Clear();
dataGrid.SelectedCells.Add(dataGridCellInfo);
dataGrid.CurrentCell = dataGridCellInfo;
dataGrid.BeginEdit();
}
_hasHadInitialFocus = true;
}
}

Resources