Navigation between rows in DataGrid - c#

I have created a sqlite database which is loaded in DataGrid but I have two Next and Previous Buttons, it is easy to navigated between data and show it to corresponding textbox in Windows Forms with DataGridView but I am unable to find a way to do same in DataGrid .
Here is my sql database code -
string dbConnectionString = #"Data Source=emsdatabase.db;version=3;";
Loading data into DataGrid :
SQLiteConnection sqliteCon = new SQLiteConnection(dbConnectionString);
try
{
sqliteCon.Open();
string Query = "select Eid,Name,Mobile,Gender,Email from employeeinfo";
SQLiteCommand createCommand = new SQLiteCommand(Query, sqliteCon);
createCommand.ExecuteNonQuery();
SQLiteDataAdapter dataAdp = new SQLiteDataAdapter(createCommand);
DataTable dt = new DataTable("employeeinfo");
dataAdp.Fill(dt);
TableDataGrid.ItemsSource = dt.DefaultView;
dataAdp.Update(dt);
sqliteCon.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
I can display selected data in corresponding textboxes:
DataGrid gd = (DataGrid)sender;
DataRowView rowSelected = gd.SelectedItem as DataRowView;
if (rowSelected != null)
{
EidTextBox.Text = rowSelected["Eid"].ToString();
NameTextBox.Text = rowSelected["Name"].ToString();
MobileTextBox.Text = rowSelected["Mobile"].ToString();
GenderTextBox.Text = rowSelected["Gender"].ToString();
EmailTextBox.Text = rowSelected["Email"].ToString();
}
But Unable to show corresponding data on textbox on next or previous button click
private void PrevButton_Click(object sender, RoutedEventArgs e)
{
//?????
}
private void NextButton_Click(object sender, RoutedEventArgs e)
{
//?????
}

The trick is to change SelectedIndex or SelectedItem.
private void PreviousClick(object sender, RoutedEventArgs e)
{
if (TableDataGrid.SelectedIndex > 0)
TableDataGrid.SelectedIndex--;
}
private void NextClick(object sender, RoutedEventArgs e)
{
if (TableDataGrid.SelectedIndex < TableDataGrid.Items.Count - 1)
TableDataGrid.SelectedIndex++;
}
We can find previous and next DataRowView in DataView (except when very first or last rows are selected respectively). If navigation is possible, then change DataGrid.SelectedItem:
private void PreviousClick(object sender, RoutedEventArgs e)
{
DataRowView rowSelected = TableDataGrid.SelectedItem as DataRowView;
if (rowSelected == null)
return;
int idx = GetDataRowViewIndex(rowSelected);
if (idx > 0)
TableDataGrid.SelectedItem = rowSelected.DataView[idx - 1];
}
private void NextClick(object sender, RoutedEventArgs e)
{
DataRowView rowSelected = TableDataGrid.SelectedItem as DataRowView;
if (rowSelected == null)
return;
int idx = GetDataRowViewIndex(rowSelected);
if (idx < rowSelected.DataView.Count - 1)
TableDataGrid.SelectedItem = rowSelected.DataView[idx + 1];
}
int GetDataRowViewIndex(DataRowView row)
{
for (int i = 0; i < row.DataView.Count; i++)
if (row.DataView[i] == row)
return i;
return -1;
}

Related

C# Linq To SQL to Fill a DataGrid and and get fields into a TextBox

In C# i can easily get data from a SQL DataBase and put it in a DataGrid with this code :
private void GetPcListBtn_Click(object sender, RoutedEventArgs e)
{
string service = (string)ServiceCB.SelectedValue;
comm = new SqlCommand("select T_COLLABORATEURS.CO_IDENT,T_PC.PC_ID,T_PC.PC_NOM,T_PC.PC_MODEL," +
"T_PC.PC_DATE_MES,T_PC.PC_COMM,T_PC.SERV_ID from T_COLLABORATEURS, T_PC" +
$" where T_COLLABORATEURS.CO_ID = T_PC.CO_ID and T_PC.SERV_ID = '{service}' ", conn);
SqlDataAdapter dap = new SqlDataAdapter(comm);
DataTable dt = new DataTable();
dap.Fill(dt);
PC_DT.ItemsSource = dt.DefaultView;
}
Then on Datagrid SelectionChanged Event i can click on a row to get fields datas and put it in a texbox with this code :
// DataGrid SelectionChanged => Fill TexBox
private void PC_DT_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (PC_DT.SelectedItem is DataRowView oData)
{
string pcNom = (string)oData["PC_NOM"];
string pcModel = (string)oData["PC_MODEL"];
RefPcTxtBox.Text = $"{pcNom} / {pcModel}";
}
}
Now in a other application i want to use Linq To SQL to do exactly the same.
Fill DataGrid :
// Fill DataGrid
private void GetPcListBtn_Click(object sender, RoutedEventArgs e)
{
string service = (string)ServiceCB.SelectedValue;
DataClasses1DataContext dc = new DataClasses1DataContext();
var pcCo = from co in dc.T_COLLABORATEURS
join pc in dc.T_PC on co.CO_ID equals pc.CO_ID
where pc.SERV_ID == service
select new
{
pc.PC_ID,
co.CO_IDENT,
pc.PC_NOM,
pc.PC_MODEL,
pc.PC_DATE_MES,
pc.PC_COMM,
pc.SERV_ID
};
PC_DT.ItemsSource = pcCo;
}
But now how can i fill my TextBox by clicking a DataGrid row ??
private void PC_DT_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// How to Fill my Textbox ??
}
Please try this.
First way:
// Or whenever grid you want to use please set this type
var Grid = sender as DataGrid;
if(Grid != null)
{
textbox = Grid.FieldName
}
Second way:
var currentRow = GridName.SelectedRows;
if(currentRow != null)
{
textbox = currentRow .FieldName
}

ComboBoxCell Value is not valid

I have a datagridview binded to a BindingList and inside this list I have comboboxes binded to a list which is a property of my BindingList, for understanding better:
ListA ---> binded to datagridview
ListA.ListB ---> binded to comboboxes
When I open the form I can corectly set my comboboxes showing the values inside the ListB, but when I add a new item I get an error (value is not valid), here is the code:
private void dataGridView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
((DataGridViewComboBoxColumn)dataGridView.Columns["Names"]).DisplayIndex = 4;
for (int i = 0; i < People.Count; i++)
{
var cell = (DataGridViewComboBoxCell)dataGridView.Rows[i].Cells["Names"];
cell.DataSource = People[i].Names;
cell.Value = People[i].Names[0];
}
}
The code above works great, the problem happens here:
private void dataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (dataGridView.CurrentCell.ColumnIndex != dataGridView.Columns["Names"].Index)
return;
var cell = (DataGridViewComboBoxCell)dataGridViewICAO.CurrentCell;
if (cell.EditedFormattedValue.ToString().Equals(String.Empty)) return;
var regex = new Regex("[a-zA-Z]");
if (!regex.IsMatch(cell.EditedFormattedValue.ToString()))
e.Cancel = true;
else
{
People[cell.RowIndex].Names.Add(cell.EditedFormattedValue.ToString());
cell.Value = People[cell.RowIndex].Names.Last();
People[cell.RowIndex].Names = cell.Value.ToString();
}
}
on the row code cell.Value = People[cell.RowIndex].Names.Last(); I get the exception... Thanks to all!
This is how I set the combobox:
private void AddComboBox()
{
var comboNames = new DataGridViewComboBoxColumn { Name = "cmbNames", HeaderText = "Names" };
dataGridView.Columns.Add(comboNames);
}
private void dataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (dataGridView.CurrentCell.ColumnIndex == dataGridView.Columns["cmbNames"].Index)
{
var combo = e.Control as ComboBox;
if (combo == null)
return;
combo.DropDownStyle = ComboBoxStyle.DropDown;
}
}

How can i get my datagridview code let work in a datagrid

I have create a win forms with a datagridview. Where i can insert update delete
articles from the database.
But i need a wpf not a win forms project. The problem is in wpf you don't have a datagridview.
Now i have try for let work it with a datagrid but there are no row options.
i have already found how i can load the data from the wcf in my datagrid with this DgArtikel.ItemsSource = ds.Tables[0].DefaultView;
but how can i let work the insert update and delete button ?
public partial class Form1 : Form
{
ServiceReference1.Service1Client objService = new ServiceReference1.Service1Client(); // Add service reference
public Form1()
{
InitializeComponent();
showdata();
}
private void showdata() // To show the data in the DataGridView
{
DataSet ds,ds2 = new DataSet();
ds = objService.SelectUserDetails();
ds2 = objService.SelectCombobox();
dataGridView1.DataSource = ds.Tables[0];
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
ComboBoxCategorie.DataSource = ds2.Tables[0];
ComboBoxCategorie.DisplayMember = "Categorie";
}
private void btnClear_Click(object sender, EventArgs e)
{
int i = dataGridView1.SelectedCells[0].RowIndex;
textBoxArtikel.Text = dataGridView1.Rows[i].Cells[1].Value.ToString();
textBoxOmschrijving.Text = dataGridView1.Rows[i].Cells[2].Value.ToString();
textBoxVerkoopprijs.Text = dataGridView1.Rows[i].Cells[3].Value.ToString();
textBoxInStock.Text = dataGridView1.Rows[i].Cells[4].Value.ToString();
ComboBoxCategorie.SelectedValue = dataGridView1.Rows[i].Cells[5].Value.ToString();
}
private void btnSave_Click(object sender, EventArgs e)
{
ServiceReference1.UserDetails objuserdetail = new ServiceReference1.UserDetails(); // Add type reference
// objuserdetail.UserID = count;
objuserdetail.Artikel = textBoxArtikel.Text;
objuserdetail.Omschrijving = textBoxOmschrijving.Text;
objuserdetail.Verkoopprijs = Convert.ToInt32(textBoxVerkoopprijs.Text);
objuserdetail.Instock = Convert.ToInt32(textBoxInStock.Text);
objuserdetail.Cat_id = ComboBoxCategorie.SelectedIndex;
objService.InsertUserDetails(objuserdetail); // To insert the data
showdata();
}
private void btnDelete_Click(object sender, EventArgs e)
{
ServiceReference1.UserDetails objuserdetail = new ServiceReference1.UserDetails();
if (dataGridView1.Rows.Count > 1)
{
DataTable dt = new DataTable();
// objuserdetail.UserID = (int)dataGridView1.CurrentRow.Cells[0].Value;
objService.DeleteUserDetails(objuserdetail); // To Delete the data
showdata();
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
ServiceReference1.UserDetails objuserdetail = new ServiceReference1.UserDetails();
objuserdetail.Artikel_id = (int)dataGridView1.CurrentRow.Cells[0].Value;
objuserdetail.Artikel = textBoxArtikel.Text;
objuserdetail.Omschrijving = textBoxOmschrijving.Text;
objuserdetail.Verkoopprijs = Convert.ToInt32(textBoxVerkoopprijs.Text);
objuserdetail.Instock = Convert.ToInt32(textBoxInStock.Text);
objService.UpdateRegistrationTable(objuserdetail); // To Update the Data
showdata();
textBoxArtikel.Text = "";
textBoxOmschrijving.Text = "";
textBoxVerkoopprijs.Text = "";
textBoxInStock.Text = "";
}
}
}

Gridview always show previous selected row

I am updating gridview after selecting row and then clicking edit which works perfectly but one thing is annoying me that whenever i visit that gridview that it shows that ROW SELECTED and Colored. Why ? i want fresh gridview with no record of previous selected data.
CODE:
protected void Page_Load(object sender, EventArgs e)
{
if (Session.Count <= 0)
{
Response.Redirect("login.aspx");
}
lblMsgPopUp.Visible = false;
}
protected void btnUpdatePopUp_Click(object sender, EventArgs e)
{
try
{
int ComplainantTypeID = Convert.ToInt32(txtSelectedID.Text.Trim());
ComplainantTypeBizz comBizz = new ComplainantTypeBizz(txtName.Text);
ManageComplainantType mngComplainantType = new ManageComplainantType();
bool Result = mngComplainantType.Update(comBizz, ComplainantTypeID);
if (Result == true)
{
HiddenFieldSetMessage.Value = "Updated";
HiddenFieldShowMessage.Value = "True";
Clear(txtName);
}
else
{
HiddenFieldSetMessage.Value = "NotUpdated";
HiddenFieldShowMessage.Value = "True";
}
}
catch (Exception)
{
HiddenFieldSetMessage.Value = "NotUpdated";
HiddenFieldShowMessage.Value = "True";
}
}
You have to bind the data to the gridview (GridView.DataBind();) after you edit it in the RowUpdated event and set the GridView.SelectedIndex = -1; after each data bind to unselect any row in your grid.
protected void GridView1_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
GridView1.DataBind();
GridView1.SelectedIndex = -1;
}
Hope this helps.

checking if gridview has a selected item

I have a grideview and 2 buttons. I need to only show the buttons when the gridview has a selected item. My code looks like this:
protected void Page_Load(object sender, EventArgs e)
{
btactivate.Visible = false;
btdeactivate.Visible = false;
//Show Activate and Deactivate Buttons only if an item in the gridview is selected
if (GridView1.SelectedIndex != -1)
{
btactivate.Visible = true;
btdeactivate.Visible = true;
}
else
{
btactivate.Visible = false;
btdeactivate.Visible = false;
}
}
But the problem I have now is that only when I select the second time a item in the gridview the buttons show up. I need to have the the buttons show when I select the first time. I have tried changing the selected index to "-0" but that shows the buttons all the time (even when I dont have something selected). Can anyone please help?
Try this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.Add("Col1");
dt.Columns.Add("Col2");
dt.Columns.Add("Col3");
for (int i = 0; i < 20; i++)
{
DataRow dr = dt.NewRow();
dr["Col1"] = string.Format("Row{0}Col1", i + 1);
dr["Col2"] = string.Format("Row{0}Col2", i + 1);
dr["Col3"] = string.Format("Row{0}Col3", i + 1);
dt.Rows.Add(dr);
}
GridView1.DataSource = dt;
GridView1.DataBind();
SetButtonState();
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
SetButtonState();
}
private void SetButtonState()
{
btactivate.Visible = GridView1.SelectedIndex > -1;
btdeactivate.Visible = GridView1.SelectedIndex > -1;
}

Categories

Resources