Get GridView row index from a template field button - c#

first question:
I have a gridview 'gvSnacks' with a list of snacks and prices. The first column of the gridview is a templatefield with the button 'btnAdd'.
When one of the add buttons is clicked I want it to assign that rows value to an integer so I can retrieve additional data from that row.
This is what I have, but I've hit a dead end.
protected void btnAdd_Click(object sender, EventArgs e)
{
int intRow = gvSnacks.SelectedRow.RowIndex;
string strDescription = gvSnacks.Rows[intRow].Cells[2].Text;
string strPrice = gvSnacks.Rows[intRow].Cells[3].Text;
}
Appreciate any help!

You may need to use the RowCommand Event :
public event GridViewCommandEventHandler RowCommand
This is the MSDN link for this event.
The button must have the CommandName attribute and you can put the value of the row in the command argument :
void ContactsGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked.
if(e.CommandName=="Add")
{
// Convert the row index stored in the CommandArgument
// property to an Integer.
int index = Convert.ToInt32(e.CommandArgument);
// Retrieve the row that contains the button clicked
// by the user from the Rows collection.
GridViewRow row = ContactsGridView.Rows[index];
// Create a new ListItem object for the contact in the row.
ListItem item = new ListItem();
item.Text = Server.HtmlDecode(row.Cells[2].Text) + " " +
Server.HtmlDecode(row.Cells[3].Text);
// If the contact is not already in the ListBox, add the ListItem
// object to the Items collection of the ListBox control.
if (!ContactsListBox.Items.Contains(item))
{
ContactsListBox.Items.Add(item);
}
}
}

Related

How to select a row in a DataGridView programmatically AND trigger DataGridView.SelectionChanged event?

For the life of me I cannot seem to figure this out. I have a long DataGridView (that does not allow MultiSelect) and when a user commits a change to the data, the data from the grid is purged and redrawn (because changes can affect multiple rows, this was the simpler approach). However, when I try to select the row programmatically, it does not also fire the DataGridView.SelectionChanged event, which I use to display data from an array which is correlated to the DataGridView current cell index. When doMagicStuff executes, the values for the wrong index (specifically, index 0) is show.
private void doMagicStuff()
{
int selRow = myDGV.CurrentCell.RowIndex;
myDGV.Rows.Clear();
/*Perform Task, Redraw data*/
myDGV.CurrentCell = myDGV[selRow, 0];
}
private void myDGV_SelectionChanged(object sender, EventArgs e)
{
Label1.Text = myDisplayValue1[myDGV.CurrentCell.RowIndex];
Label2.Text = myDisplayValue2[myDGV.CurrentCell.RowIndex];
TextBox1.Text = myEditValue1[myDGV.CurrentCell.RowIndex];
TextBox2.Text = myEditValue2[myDGV.CurrentCell.RowIndex];
}
Make sure that your client settings and OnSelectedIndexChanged is set like so: (ASP.NET AJAX)
.aspx page
<telerik:RadGrid ID="Grid1" runat="server" OnSelectedIndexChanged="Grid1_SelectedIndexChanged" OnItemDataBound="Grid1_ItemDataBound" OnPreRender="Grid1_PreRender">
<ClientSettings EnablePostBackOnRowClick="true">
<Selecting AllowRowSelect="true"></Selecting>
</ClientSettings>
</telerik:RadGrid>
aspx.cs page
protected void Grid1_SelectedIndexChanged(object sender, EventArgs e)
{
string value = null;
foreach(GridDataItem item in Grid1.SelectedItems)
{
//column name is in doub quotes
value = item["Name"].Text;
}
}
Add a button click to the form to test the selected values in the DataGridView.. double click that button then paste this code in there
foreach (DataGridViewRow row in myDGV.SelectedRows)
{
Label1.Text = //This should be hard coded the only thing that should change dynamically is the TextBox Values
Label2.Text = //This should be hard coded the only thing that should change dynamically is the TextBox Values
TextBox1.Text = row.Cells[0].Value.ToString();//change the 0 or 1 to fit your column Index position
TextBox2.Text = row.Cells[2].Value.ToString();
}
also if you have 4 columns and 4 text boxes then you will assign all of the textbox.Text values within the foreach loop just follow the pattern and increase the index by 1 so 2 textboxes means row.Cells[0] is the first column row.Cells[1] is the second column ...etc

How to get a Telerik Multi column combo box value which is a column in rad grid view?

I want to get the first element of telerik multi combo box which is a column of a telerik grid view
when user selects a row i want to get the first element of that row and pass it to my DB
i've done some thing but i geuss it's not enough
if (Ref_MultiColumnComboBox.MultiColumnComboBoxElement.SelectedIndex >= 0)
{
var tr = Ref_MultiColumnComboBox.MultiColumnComboBoxElement
.EditorControl.Rows[Ref_MultiColumnComboBox.MultiColumnComboBoxElement.SelectedIndex]
.Cells["Id"].Value.ToString();
MessageBox.Show("m= {0}" + " // " + tr);
}
else
{
MessageBox.Show("", "Error");
}
the problem is that when user selects some row or doesn't selectedindex is allways -1
Here is one way to do it for RadMultiColumnComboBox control:
void radMultiColumnComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewDataRowInfo selectedRow = (GridViewDataRowInfo)radMultiColumnComboBox1.SelectedItem;
Console.WriteLine(selectedRow.Cells["Id"].Value.ToString());
}
The SelectedItem provides a reference to the selected row in the inner grid, from where you can access its cells and values.
If GridViewMultiComboBoxColumn is used, then you can use either the ValueChanged event, or the CellValueChangned events to get the row of the currently selected item:
void radGridView1_CellValueChanged(object sender, GridViewCellEventArgs e)
{
RadMultiColumnComboBoxElement mccbEditor = (RadMultiColumnComboBoxElement)e.ActiveEditor;
GridViewDataRowInfo selectedRow = (GridViewDataRowInfo)mccbEditor.SelectedItem;
Console.WriteLine(selectedRow.Cells["Id"].Value.ToString());
}
void radGridView1_ValueChanged(object sender, EventArgs e)
{
RadMultiColumnComboBoxElement mccbEditor = (RadMultiColumnComboBoxElement)radGridView1.ActiveEditor;
GridViewDataRowInfo selectedRow = (GridViewDataRowInfo)mccbEditor.SelectedItem;
Console.WriteLine(selectedRow.Cells["Id"].Value.ToString());
}

Display gridview row count based on dropdown selection

I am using this code to take a gridview count and display in a label on page load and works fine.
Page Load:
int rowCount = dtDetails.Rows.Count;
lblTotalRows.Text = rowCount.ToString() + "records found";
I have a dropdown above my gridview and when I select dropdown values the row count have to changed based on the dropdown selected values.
How could I possibly do that in dropdown selected index change
protected void ddlGroup_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable dtGroup = DataRepository.GetGroup(ddlGroup.Text);
gvDetails.DataSource = dtGroup;
gvDetails.DataBind();
//Now how could I possible show the respective row counts in the label
}
protected void ddlGroup_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable dtDept = DataRepository.GetDept(ddlGroup.Text, ddlDept.Text);
gvDetails.DataSource = dtDept;
gvDetails.DataBind();
//Now how could I possible show the respective row counts of both group and
dept row count since they are cascading dropdowns in the label
}
Any suggestions?
I tend to make a SetData() method so all this kind of code is in one place. So in this instance I would:
protected void SetData(DataTable dtGroup)
{
// Bind the data to the grid
gvDetails.DataSource = dtGroup;
gvODetails.DataBind();
// Show row count
if (!dtGroup.Rows.Count.Equals(0))
lblTotalRows.Text = dtGroup.Rows.Count + " records found";
else
lblTotalRows.Text = "No records found";
}
This way you only have one place that does all the 'bindind' so in your Page_Load you can just call this SetData() method and pass in the datatable, and the same on your SelectedIndexChanged.

Add hyperlink like functionality in win forms

My motive is to display some information as link and on click of that, I should be able to get id of clicked item and open new window with detailed information of item. As i am new in win forms but i did some research, Possible option for this might be DataGridViewLinkColumn but i am not able to link id with column data and click event on which open new window.
Or there any other better approach possible.?
When you have a datagridview you can get the values of a cell as follows:
Firstly, create a cellclick event
datagridview1.CellClick+= CellClickEvent;
DataGridViewCellEventArgs holds some properties, these would be rowindex (row you clicked) and columnindex (column you clicked) and some other...
make a datagrid with 2 columns, column 0 holds the Id of the row, column 1 holds the link
void CellClickEvent(object sender, DataGridViewCellEventArgs e)
{
if(e.ColumnIndex == 1) // i'll take column 1 as a link
{
var link = datagridview1[e.columnindex, e.rowindex].Value;
var id = datagridview1[0, e.rowindex].Value;
DoSomeThingWithLink(link, id);
}
}
void DoSomeThingWithLink(string link, int id)
{
var myDialog = new Dialog(link,id);
myDialog.ShowDialog();
myDialog.Dispose(); //Dispose object after you have used it
}
I'm assuming you're using a DataGridView element.
What you could do is use the CellClick event of the object. It will have a DataGridViewCellEventArgs object passed on, on which there's a ColumnIndex property and a RowIndex property. This way you could figure out where in the the datagrid the user clicked.
And, for example, you could use that information to look up the id or other info since you now know the row & the cell the user clicked on.
arbitrary e.g.:
// wire up the event handler, this could be anywhere in your code
dataGridView.CellClick += dataGridView_CellClick; // when the event fires, the method dataGridView_CellClick (as shown below) will be executed
private void dataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
var rowIndex = e.RowIndex;
var columnIndex = e.ColumnIndex; // = the cell the user clicked in
// For example, fetching data from another cell
var cell = dataGridView.Rows[rowIndex].Cells[columnIndex];
// Depending on the cell's type* (see a list of them here: http://msdn.microsoft.com/en-us/library/bxt3k60s(v=vs.80).ASPX) you could cast it
var castedCell = cell as DataGridViewTextBoxColumn;
// Use the cell to perform action
someActionMethod(castedCell.Property);
}
(*DataGridViewCell types: http://msdn.microsoft.com/en-us/library/bxt3k60s(v=vs.80).ASPX)

How to transfer data from gridview to textbox

Suppose if I say I have selected a row in gridview and want that row to come up in to their respective textboxes. For example, I have selected a row which has First Name and Last Names and on selection of row, the data from gridview should come in to textbox on winform. Please tell me.
I am guess it is something based on selection changed event if I am right ? Like below:
private void dgv_SelectionChanged(object sender, EventArgs e)
{
string str = txtFirstName.Text;
DataGridViewRow selectedRow;
}
If I got your question right, your solution is to use DataGridView.SelectedRows Property along with DataGridView.SelectionChanged Event
DataGridView.SelectedRows Gets the collection of rows selected by the
user.
DataGridView.SelectionChanged occurs whenever cells are selected or
the selection is canceled, whether programmatically or by user action.
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count > 0)
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows) {
//Send the first cell value into textbox'
Txt_FirstName.Text = row.Cells(0).Value.ToString; // or row.Cells["ColumnName"].Value;
}
}
}
MSDN and MSDN

Categories

Resources