Determining what is selected in a data grid view and running queries? - c#

I have a data grid view with my table information in there. Just don't know how to know what the use selected. Then once I have that figured out how to get a value that is selected and run a query to my database with it.
My tables have a GUID and nothing really else to use to run queries off of. Should I use something else or is there a way to use the GUID to find and do querys on it?

Have you tried using the _SelectedIndexChanged event?
when using query's below change [GridViewName] to the ID of your gridview
to then get the row use.
GridViewRow row = [GridViewName].Rows[e.NewSelectedIndex];
then to get individual cell values you can then use.
row.Cells[1].Text;
to run a query with it I would recommend using the two like this.
void [GridViewName]_SelectedIndexChanged(Object sender, [GridViewName]SelectEventArgs e)
{
GridViewRow row = [GridViewName].Rows[e.NewSelectedIndex];
if (row.Cells[1].Text == "ABCDE")
{
//do database stuff here
}
}
If you want to run a query to get children add the PK of your database table to the gridview in the first Column. Then use below code to get the PK value and you will be able to run queries.
[GridViewName]_SelectedIndexChanged(Object sender, [GridViewName]SelectEventArgs e)
{
//gets the current selected row
GridViewRow row = [GridViewName].Rows[e.NewSelectedIndex];
// gets the the PK for running querys
string PKselectedRow = row.Cells[0].Text
}
Here is the Microsoft documentation on GridViewRow. http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridviewrow(v=vs.110).aspx

Related

How to add textbox value to datagrid cell using query c#

I'm creating a windows form that will allow my group at work to check in & out computers from our spare cabinet. I have two tables, an 'Assets' table & Inventory Log table. The user will fill out the GUI and select the asset they want from the check out screen. The problem I am having is trying to pass the foreign key 'InventoryID' to the log table. I have the main textbox's bound to datagrid cells but I am unable to do this with the inventory ID because I have it bound to a textbox so the user does not have to enter it every time.
I have tried creating an insert query that takes the textbox and converts it to int and then inserts it into the method but it catches an exception. Note, this query works when I test it in the query builder. I have also tried adding it with the binding source property but it cant find the index.
private void BtnSubmit_Click(object sender, EventArgs e)
{
//get asset number
string asset = txtAssetNumber.Text;
//get invID from textbox
int InventoryID = Convert.ToInt32(txtinv.Text);
//this query changes available status to 'No'
inventoryTableAdapter.SetNo(asset);
//runs query to determine what rows have 'Yes'
inventoryTableAdapter.Available(this.loanerCabDataSet.Inventory);
try
{
//add new row to log table
inventoryLogBindingSource.AddNew();
//suppose to insert the ID into table
inventoryLogTableAdapter.insertinvid(InventoryID);
//set textbox back to today's date
txtOutDate.Text = DateTime.Today.ToString("MM/dd/yyyy");
this.Validate();
this.inventoryBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.loanerCabDataSet);
MessageBox.Show("Success");
}
catch (Exception)
{
throw;
}
}
Query:
INSERT INTO InventoryLog (InventoryID)
VALUES (?)
Finally figured out a way around it.
Created insert query and instead of binding all of the textboxes to the column, I created variables and passed them into the function.
Heres what it looks like now.
inventoryLogTableAdapter.Insert(InventoryID, customer, tech, loaneddate, datein, location, ticket, notes);

Best way to auto-increment ID column in a DataGridView?

I have a dataGridView in which I can insert, delete and update values but something is bothering me.
The user can only modify the 2 columns that are displayed (size and quantity), 2 others are hidden (ID and chosenComponent).
ID is PK in my table.
This is what I did to set ID and chosenComponent of new rows :
private void dataGridViewStock_DefaultValueNeeded(object sender,
System.Windows.Forms.DataGridViewRowEventArgs e)
{
e.Row.Cells["id"].Value = "1";
e.Row.Cells["codeArticleComponent"].Value = labelComponentChosen.Text;
}
Whatever value I put for the ID, the first available number will be inserted to the database. It works but I'm afraid it might later cause bugs.
Is there a better way to achieve this ? Or can I leave it as is ?
You may need a separate column(Only in the GirdView) to identify whether the current row is newly added or existing one. And increment id column with negative values based on the new column.
While saving the data you can identify the newly created rows, based on that you can save the data by inserting without id column or update the existing data.
Hope this clarifies you.
This is my code for the auto-increment primary key in a datagrid view
private void Row_Added(object sender,
DataGridViewRowsAddedEventArgs e){
foreach(DataGridViewRow dtr in dataGridView1.Row){
dataGridView1.Rows[e.RowIndex-1].Cells[0].Value =
e.RowIndex;
}
}
i used this...

Stored Proceedure or GridView DataSource

I've built a frontend to update an individual column for selected records in a GridView. I've gotten that all setup the way that I want it to work including performing a check to be sure that more than one row is selected (via a template field checkbox I added to the GridView) and that a column has been selected from a dropdown list.
I have everything down to the block of code that has to be built to do the actual update of the column for the selected rows. This will cycle through each row, so if I've selected 5 rows it would trigger this code 5 times and update the record ID associated with that row.
I'm mainly debating with myself which would be the simplest to build into this. I at first thought about doing a stored procedure on the SQL Server and feeding it the record ID, column to update, and the value to write in the update. But then I got to thinking about it and realized that I have a GridView with a Data Source that was already setup to update the record as long as I called it
In either case I'll need to refresh the GridView after the update has been completed.
Just wondering what others might think would be the cleanest approach to this and just what my options might be. I've never seen a multi row column edit implemented so figure someone may have a better idea than me on how to go about this.
Here is my code block for the update as it is right now...
protected void SaveColEditBtn_Click(object sender, EventArgs e)
{
//Read the column select drop down List into Local Varriables
String SelectedColumnItem = ColumnSelectDDL.SelectedItem.ToString();
String SelectedColumnValue = ColumnSelectDDL.SelectedValue.ToString();
List<int> EditRows = new List<int>();
List<string> recordnumber = new List<string>();
foreach (GridViewRow grv in ActVulListGV.Rows)
{
if (((CheckBox) grv.FindControl("TagRowChkBx")).Checked == true)
{
//get current row rowindex if checkbox in it is checked
EditRows.Add(grv.RowIndex);
//get the record number (RecID)
recordnumber.Add(grv.Cells[2].Text.ToString());
}
}
int[] ERows = EditRows.ToArray();
if (recordnumber.Count > 1)
{
if (ColumnSelectDDL.SelectedValue.ToString() == "TicketNumber")
{
// Save Ticket number //
}
else if (ColumnSelectDDL.SelectedValue.ToString() == "TicketClosed")
{
// Save Ticket Closed Value //
}
else if (ColumnSelectDDL.SelectedValue.ToString() == "Notes")
{
// Save Notes //
}
else if(ColumnSelectDDL.SelectedValue.ToString() == "Exception_ID")
{
// Save Exception ID //
}
EditColMsgLbl.Font.Bold = true;
SelectedRowsMsgLbl.Font.Bold = true;
ColEditPnlExt.Show();
EditColLbl.Text = SelectedColumnItem;
SelectedRowsLbl.Text = "";
foreach (string record in recordnumber)
{
// Insert the call of the procedure here to update the database
}
}
else
{
UserMessageLbl.Text = " *** Choose 2 or more rows to use column edit feature! ***";
mpePopUp.Show();
}
}
It depends. If you are updating all at once, by looping, use a Stored Procedure. However updating one by one with EditIndex, it is easier to use the source. However I would recommend using code behind and a SP to update a row, then you could use the same SP for updating a single or all rows.
See this excellent tutorial. It covers all the basics of GridView editing and updating.
And a tip if you have some time to spare in the near future, try to disable ViewState for the GridView. It will save a lot of tranfer kb's and overhead. But get the above to work first ;)

Remove & Update Selected Row or Item from Datagrid In WPF

I am trying to remove selected row of datagrid from database. I am able to save data in database but I don't know how to delete. I am using SQLITE Database.
Note: I am using DataGrid not datagridview.
Try this :
private void DeleteButtonClick(object sender, MouseEventArgs e)
{
if (dataGrid.SelectedItem == null)
return;
DataRowView rowView = (DataRowView)dataGrid.SelectedItem; // Assuming that you are having a DataTable.DefaultView as ItemsSource;
DB.Execute("DELETE FROM TABLE WHERE myCol=" + rowView["myCol"]); // rowView[ColumnName] retrieves the value for you, Use your Primary Column's name here;
}
This should help you :)
Create a query using the DELETE statement. Something like
$"DELETE FROM table WHERE id = {row["id"]}"

How do I extract specific values from SELECTED/HIGHLIGHTED rows on a GridVIew in ASP .NET?

I have a GridView with data. The first column on this GridView is the "SELECT" column.
If the user clicks on SELECT, it highlights the entire row.
I have an event on this click action:
protected void gvShows_SelectedIndexChanged(object sender, EventArgs e)
{
}
Basically what I want to do is for each SELECTED row, I want to extract the values for the columns:
dataSource
showId
episodeId
**Here's where I'm having problems:
string dataSource = "";
int showId = 0;
int episodeId = 0;
foreach (DataRow row in gvShows.Rows)
if (the row is selected/highlighted then...)
{
dataSource = the value under column "dataSrouce" for this ROW.
showId = the value under column "showId" for this ROW.
episodeId = the value under column "episodeId" for this ROW.
}
Can anyone give me a hand with this?
I believe you will want to use SelectedIndexChanging (and not SelectedIndexChanged) because that will give you access to the new selected row index. If the first cell is the button, the next three should give you the values you need:
protected void gvShows_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
GridViewRow r = gvShows.Rows[e.NewSelectedIndex];
string dataSource = r.Cells[1].Text;
int showId = Convert.ToInt32(r.Cells[2].Text);
int episodeId = Convert.ToInt32(r.Cells[3].Text);
}
Edit:
I wanted to add that you can use the SelectedIndexChanged if you didn't want to use SelectedIndexChanging:
protected void gvShows_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow r = gvShows.Rows[gvShows.SelectedIndex];
string dataSource = r.Cells[1].Text;
int showId = Convert.ToInt32(r.Cells[2].Text);
int episodeId = Convert.ToInt32(r.Cells[3].Text);
}
And if you are working with a database, you can add a datakey to the gridview, allowing you to pull the primary key for the record you want to work on.
Add the following to your gridview:
DataKeyNames="showId"
And then you can access this value from the codebehind:
int showId = Convert.ToInt32(gvShows.DataKeys[gvShows.SelectedIndex].Value);
You need to rely on the "selected/highlighted" rows' attributes. Find any attribute that could determine if it is a selected row.
EventArgs e should have a Row property that represents the selected row. Within there, you have access to each of the columns (called Cells). You get into each particular cell using indexing. So, if ShowId is in column 3, here's how you'd access it:
e.Row.Cells[2]; (remember, it's 0-based indexing in C#).
First to get ShowId, try e.Row.Cells[2].Text; That might get you what you need.
If that doesn't work, try this:
Now, within Cells[2], you have access to Controls, which again is a list of controls in that cell. Run your code, and put a breakpoint inside of SelectedIndexChanged. Then in your immediate window, type the code above, and hover your mouse over Cells[2] to open up the items in there. Hover again on Controls, and look at what's in there.
Usually there's a LiteralControl, then your control with ShowId, then another LiteralControl.
Validate that, and then you'll be able to access it like e.Row.Cells[2].Controls[1].Text or something like that.

Categories

Resources