How to get field value of selected Row Devexpress GridView? - c#

I use a DevexpressGridView to display all TOPIC (id,title,content)
<dx:ASPxGridView ID="gv" runat="server"
OnSelectionChanged="gv_SelectionChanged" >
I have grid_SelectionChanged event:
protected void gv_SelectionChanged(object sender, EventArgs e)
{
int id= selected row...???; //how can I get the value of selected row
string sql = "select * from TOPIC where idTOPIC="+id;
DataTable topic = l.EXECUTEQUERYSQL(sql);
TextBox1.Text = topic.Rows[0][1].ToString();
}
...
It seems gv.SelectedRow method isn't exist in DevGridview.
As recommended, I've tried with FocusedRowIndex method, but I really dont know the right syntax to get the value of selected row.
Help!!!

Changing the selection is different from changing the focused row. See the documentation for Selection for the difference between the two.
You can use gv.GetSelectedFieldValues to get the rows which are selected.
var ids = gv.GetSelectedFieldValues("id");
foreach( var id in ids )
DoSomethingWithObject(id);
You should handle the FocusedRowChanged event if you're interested in the focused row.
You can use the FocusedRowIndex value to index the rows of gv.DataSource, for example:
DataTable ds = (DataTable)gv.DataSource;
var id = ds.Rows[gv.FocusedRowIndex]["id"];
or you can use var id = gv.GetRowValues(gv.FocusedRowIndex, "id").

I've found my answere here after a long time searching google:
http://www.devexpress.com/Support/Center/Question/Details/Q347704
Use the ASPxGridView.GetSelectedFieldValues method get selected row values on the server side.

You can also get selected data row as
int rowHandle = gridView1.FocusedRowHandle;
if (rowHandle != DevExpress.XtraGrid.GridControl.InvalidRowHandle)
{
return this.gridView1.GetDataRow(rowHandle);
}
This would return DataRow
Please note this is when I am using Devexpress gridControl in WinForms

If you want to get only ID field value you can use this
int id = Convert.ToInt32(gv.GetRowValues(gv.FocusedRowIndex, "ID").ToString());
if you have an object you can use this
Personels selectedPersonel = gv.GetRow(gv.FocusedRowIndex) as Personels;
and get value method is
int ID = selectedPersonel.ID;

Related

c# how i can get selected rows name of gridcontrol devexpress

i want get rows values by clicked the row. How i can get rows name of GridControl?
private void btnMusteriDuzenle_Click(object sender, EventArgs e)
{
int[] celRows = ((GridView)grdMusteriListele.MainView).GetSelectedRows();
MessageBox.Show(selRows.ToString());
}
The GetSelectedRows method returns handles of the selected rows.
To retrieve row cell values, utilize the following API: GetRowCellValue, GetRowCellDisplayText:
int[] selectedRows = gridView.GetSelectedRows();
for(int i = 0, i < selectedRows.Length, i++){
int id = (int)gridView.GetRowCellValue(selectedRows[i], "Id");
//...
}
If you are using the single-selection mode(the OptionsSelection.MultiSelect property is false) you can use the following API to obtain cell values of a focused row: GetFocusedRowCellValue, GetFocusedRowCellDisplayText. These API utilized the handle of a currently focused row via the FocusedRowHandle property:
int focusedId = (int)gridView.GetFocusedRowCellValue("Id");
To learn more, take a look at Accessing Rows in Code. Row Handles help article.

Ultragrid not showing a ValueList for a certain column

I have a User Control with an Ultragrid. In a particular form where I add a ValueList. The value list will not show for the particular column I'm interested in. If I then code in another column instead by changing the index value for columns I get the value list in the column.
The code looks like:
private void AddCombo(object sender, UcUltraGen.RowClickArgs e)
{
ValueList vl;
if (!ucUltraGridMain.Grid.DisplayLayout.ValueLists.Exists("Texas"))
{
vl = ucUltraGridMain.Grid.DisplayLayout.ValueLists.Add("Texas");
}
else
{
vl = ucUltraGridMain.Grid.DisplayLayout.ValueLists["Texas"];
}
var row = e.VariantRow;
List<PcBase> list = PcBase.PcBaseList.Where(x => x.VariantId == row.Cells["Id"].Text).ToList();
AddValueList(list, vl);
ucUltraGridMain.Grid.DisplayLayout.Bands[0].Columns[1].ValueList =
ucUltraGridMain.Grid.DisplayLayout.ValueLists["Texas"];
And if I change to
...
ucUltraGridMain.Grid.DisplayLayout.Bands[0].Columns[2]
It works. How can I have changed the behavior of columns[1]?
The property in column[1] was read only that is it only had a "get" implemented. By adding a set it worked. Hope this helps someone.

Updating Records in Gridview Using EF

I have a webpage with a gridview attached to it. The gridview allows the user to update individual records. The gridview looks like this:
JobSiteID JobSite1
1 13-03
2 13-04
3 13-06
4 13-09
5 13-15
I created the following record updating event handler:
protected void changeJobSiteRecordsGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = changeJobSiteRecordsGridView.Rows[e.RowIndex];
TextBox txtJobSite = row.FindControl("txtJobSite") as TextBox;
if (txtJobSite != null)
{
using (ABCEntities4 Context = new ABCEntities4())
{
int jobSiteID = Convert.ToInt32(changeJobSiteRecordsGridView.DataKeys[e.RowIndex].Value);
JobSite obj = Context.JobSites.First(x => x.JobSiteID == jobSiteID);
obj.JobSite1 = txtJobSite.Text;
Context.SaveChanges();
changeJobSiteRecordsGridView.EditIndex = -1;
changeJobSiteRecordsGridView.DataSource = Context.JobSites;
changeJobSiteRecordsGridView.DataBind();
}
}
}
Here's my problem:
When I select to update, say row #2, on the first line, the local "row" variable indicates that the RowIndex == 1.
However, in the second line, I expect txtJobSite variable to be populated with "13-04" but VS assigns "null" to the variable.
As a result, the code flows over the if then statement below which isn't what was intended.
Any help would be greatly appreciated.
Thanks.
Check the row's cells property like this:
row.Cells[1].Controls[0]
for the text box. If the '0' index doesn't work, try the 1 index. Then your code would look something like this:
TextBox txtJobSite = (TextBox)row.Cells[1].Controls[1]
I remember running into a similar problem with FindControl. This way, you explicitly find the cell and then the control in the cell.

How to get IDs of only checked rows of a datagridview

I have a datagridview that contains list of subjects populated from Subject table from database.Columns include
Select(checkbox),
SubjectId,
SubjectName,
SubjectGroup.
Now I want if a user Selects on any of the desired rows, the corresponding SubjectId's should be added to a List. I have made and inserted into the desired table in the database.
The problem is that the new column of checkboxes I have added to this datagridview is not being detected.
My code is:
foreach (DataGridViewRow row in gvSubjectsOpted.Rows)
{
if (Convert.ToBoolean(gvSubjectsOpted.SelectedRows[0].Cells["SelectId"].Value=true))
{
olist.Add(gvSubjectsOpted.SelectedRows[0].Cells["SubjectId"].Value.ToString());
}
}
Late to the party. I had the same issue with trying to get the checkbox column by name, use the index instead. Here is a linq example assuming the checkbox is column 0 and the stored values for TrueValue and FalseVale are true and false respectively.
var checkedRows = from DataGridViewRow r in gvSubjectsOpted.Rows
where Convert.ToBoolean(r.Cells[0].Value) == true
select r;
foreach (var row in checkedRows)
{
olist.Add(row.Cells["SubjectId"].Value.ToString());
}
I realise this is an old post but I came across it and didn't think it was really answered in an efficient way so I thought I would add my method.
I have a similar block in my windows app. I read the values from the grid when the user clicks a button, and I want to know which rows they checked. As the checkboxes are in Cell 0 and the data I want is in Cell 1, I use the following code. Note the cast: it is important as it allows us the use the Where clause and therefore just a single line of code to get the collection of data. I could use the name of the cells instead of magic index numbers but then it would not fit your app so I put numbers instead (you should use names)
var checkedRows = dataGridView
.Rows
.Cast<DataGridViewRow>()
.Where(x => x.Cells[0].Value.ToString() == "1")
.Select(x => x.Cells[1]);
Note that this will give you an IEnumerable of type DataGridViewCell. If you want you can either add something like .Value.ToString() to the select or do this when you use your collection.
You question is similar to another SO question.
Check the answer of this Datagridview checkboxcolumn value and functionality.
Try this
foreach(GridViewRow r in gvSubjectsOpted.Rows)
{
GridViewCheckBoxColumn c = r.cells[0].Controls[0] as GridViewCheckBoxColumn;
if(c.Checked)
{
//Do something.
}
}
private void button1_Click(object sender, EventArgs e)
{
string subjId;
List<string> lines = new List<string>();
for (int i = 0; i < gvSubjectsList.Rows.Count; i++)
{
bool Ischecked =Convert.ToBoolean(gvSubjectsList.Rows[i].Cells["Select"].Value);
if (Ischecked == true)
{
subjId = gvSubjectsList.Rows[i].Cells["SubjectId"].Value.ToString();
lines.Add(subjId);
}
}
comboBox1.DataSource = lines;
}
//the most important thing is to set 'true' and 'false' values against newly added checkboxcolumn instead of '0' and '1'...that is,
CBColumn.FalseValue = "false";
CBColumn.TrueValue = "true";

Unable to cast object of type 'System.Data.Objects.MaterializedDataRecord'

I have a GridView connected with the EntityDataSource.
EntityDataSource has a internal parameter for Where Parameters. All is working fine till this point.
<asp:EntityDataSource ID="EntityDataSourceListAuthors" runat="server" ConnectionString="name=CmsConnectionStringEntityDataModel"
DefaultContainerName="CmsConnectionStringEntityDataModel" EnableFlattening="False"
EntitySetName="CmsAuthors" EntityTypeFilter="" OrderBy="it.FirstName" Select="it.AuthorId, it.UserId, it.FirstName, it.LastName, it.NoteInternal, it.ContentAuthor"
Where="it.UserId = #ActiveUser">
</asp:EntityDataSource>
I use an Event RowDataBound an Entity Framework to retrieve a value for every single row and execute some logic.
As soon as I run the code I receive this error:
Unable to cast object of type 'System.Data.Objects.MaterializedDataRecord' to type 'WebProject.DataAccess.DatabaseModels.CmsAuthor'.
It seems to me when adding parameters to EntityDataSource smt is changing so I am not able to use EF as before
Any idea? Thanks Guys!
protected void uxListAuthorsDisplayer_RowDataBound(object sender, GridViewRowEventArgs e)
{
switch (e.Row.RowType)
{
// In case type of row is DataRow (a data row of GridView)
case DataControlRowType.DataRow:
// Display friendly User's Name instead of his Guid
// Retrive underlying data from a single row rappresented in GridView (use Entity Framwork)
WebProject.DataAccess.DatabaseModels.CmsAuthor myRow = (WebProject.DataAccess.DatabaseModels.CmsAuthor)e.Row.DataItem;
// Retrive the Guid for a User in a specific row
Guid myUserGuid = (Guid)myRow.UserId;
// Find out used UserName using Guid UserId
MembershipUser mySelectedUser = Membership.GetUser(myUserGuid);
// Write friendly User's Name instead of his Guid value in a specific Grid View Cell
e.Row.Cells[3].Text = mySelectedUser.UserName;
// Disable Delete Button if a Content has associated an Author
// Use Entity Framwork for retriving data - Create a "Context" for a single Row
using (CmsConnectionStringEntityDataModel context = new CmsConnectionStringEntityDataModel())
{
// Find out Row Id and create an varaible to store it
int myWorkingRowId = myRow.AuthorId;
// Find the Edit Link
HyperLink myEditLink = (HyperLink)e.Row.FindControl("uxLinkEditButton");
// Find the Delete Button
LinkButton myDeleteButton = (LinkButton)e.Row.FindControl("uxLinkDeleteButton");
// Find the System Note Label
Label mySystemNote = (Label)e.Row.FindControl("uxSystemNoteDisplayer");
// Use of Lamba Espression with EF to check if an Author is associated with a Content
CmsContent authorIdInContent = context.CmsContents.FirstOrDefault(x => x.AuthorId == myWorkingRowId);
// Make visible or invisible the Delete Button if an Author is associated to a Content
if (authorIdInContent != null)
{
myDeleteButton.Visible = false;
mySystemNote.Text = "Author is being used in Contents";
}
else
{
myDeleteButton.Visible = true;
}
// Programmatically Limiting Functionality depending on User's Roles
myEditLink.Visible = User.IsInRole("CMS-ADMINISTRATOR") || User.IsInRole("CMS-AUTHOR") || User.IsInRole("CMS-EDITOR");
myDeleteButton.Visible = User.IsInRole("CMS-ADMINISTRATOR");
}
break;
}
}
Read Diego Vega's blog post on binding EntityDataSource in the RowDataBound event:
http://blogs.msdn.com/b/diego/archive/2008/05/13/entitydatasource-to-wrap-or-not-to-wrap.aspx
You are running into the fourth scenario of his "rules for wrapping".
Finally, if you set the Select property to do a projection (i.e. "it.CustomerID, it.CustomerName", you get DbDataRecord regardless of how you start your query.
You will not be able to get the source entity. You have to treat your DataItem as something like a DataRow.
If e.Row.RowType = DataControlRowType.DataRow Then
Dim rowCmsAuthor = CType(e.Row.DataItem, Data.Common.DbDataRecord)
Dim myUserID As Integer = rowCmsAuthor("UserId")
End If
Alternatively you may be able to just remove the Select property from your EntityDataSource. Try to use scenario 1 or 2 of Diego's rules for wrapping.

Categories

Resources