Edit: I solved the problem by including an filterexpression on my gridview and a textbox for the search. That way I could pass the search query directly without doing all kinds of fancy stuff.
I have made a basic searchfunction. In that searchfunction, I have included a hyperlink to see more information:
<asp:HyperLink ID="lnkSelect" runat='server' NavigateUrl='<%# String.Format("~/CompanyActive.aspx?id={0}", Eval("CompanyID")) %>'>Select</asp:HyperLink>
It passes on the CompanyID to my mainpage (CompanyActive) where I have a gridview with paging.
However my problem is that it doesnt go to the specific page/place where the record is located. It just shows the first page.
I think I need to put some kind of code into my pageload event on CompanyActive, but I dont know which commands I should be using.
are you using a datatable to fill your gridview ?
if so and you know the ID is not going to change you could do the navigation on record ID
here is a link to a similar question on Stackoverflow
How to go to particular record in gridview
Hope this helps
Martyn
Example
You are using this as your link button
<asp:HyperLink ID="lnkSelect" runat='server' NavigateUrl='<%# String.Format("~/CompanyActive.aspx?id={0}", Eval("CompanyID")) %>'>Select</asp:HyperLink>
to use the code from the other article just modify the code like this
private void BindProductGrid()
{
product ID = Request.QueryString["id"]; // id is the name same as what you passed as a querystring
DataTable tblProducts = getAllProducts();
GridProducts.DataSource = tblProducts;
bool needsPaging = (tblProducts.Rows.Count / GridProducts.PageSize) > 1;
if (ProductID == -1)
{
this.GridProducts.PageIndex = 0;
this.GridProducts.SelectedIndex = -1;
}
else
{
int selectedIndex = tblProducts.AsEnumerable()
.Select((Row, Index) => new { Row, Index })
.Single(x => x.Row.Field<int>("ProductID") == ProductID).Index;
int pageIndexofSelectedRow = (int)(Math.Floor(1.0 * selectedIndex / GridProducts.PageSize));
GridProducts.PageIndex = pageIndexofSelectedRow;
GridProducts.SelectedIndex = (int)(GridProducts.PageIndex == pageIndexofSelectedRow ? selectedIndex % GridProducts.PageSize : -1);
}
GridProducts.DataBind();
}
That way the ID is the companies id that you passed from the other page
Related
I have the following code behind:
List<Articles> articles = (from em in db.Articles orderby em.ReceivedDate descending select em).ToList();
gvArticles.DataSource = articles;
gvArticles.DataBind();
Where gvArticles is a GridView. The following is the asp code within that grid:
<p style='font-weight:bold;font-size:17px;color:black;'>
<asp:Label ID="lblDate" runat="server" Text='<%#Eval("datePrinted").ToString() %>'></asp:Label>
</p>
<asp:Label ID="lblBody" runat="server" Text= '<%#Eval("Content")%>'></asp:Label>
... that will clearly show from the DB the fields 'datePrinted' and 'Content'
Is there any way that I can show other value in 'datePrinted' based on a condition? For example, if 'datePrinted' is before 1/1/1990 then put "N/A" instead of the field 'datePrinted' itself?
Or a bit more complex, put "-" if the day is the same as the previous record (time can be different, just day/month/year is the same)?
Of course I could calculate all of that and store it in the DB, so I will pull other fields from the DB, but that sounds extremely inefficient, for any future condition create a new field in the DB. So are there any other ways to achieve the same results?
Ideally a condition, formula, or function that translates values from the DB before binding them to the grid is the most desirable solution.
Any idea?
Create a method in your code behind. Call that method parsing your value instead of using eval.
E.g
public static string ConvertDate(DateTime date)
{
if (date < new DateTime(1990, 1,1) )
{
return "N/A";
}
else
{
return date.ToString("dd/MM/yyyy");
}
}
Place this method where you placed your Eval("datePrinted").
<asp:Label ID="lblDate" runat="server" Text='<%# ConvertDate(Convert.ToDateTime(Eval("datePrinted")) ) %>'></asp:Label>
After days trying to figure out what to do, I found one answer just after posting this question. Basically I realized that you can process the List before assign it to the binding. So my second sample, I did this after loading the list and before assign it to the grid datasource:
string prevDate = "";
foreach(Article myArticle in articles) {
if (((DateTime)myArticle.ReceivedDate).ToShortDateString() != prevDate) {
prevDate = ((DateTime)myMail.ReceivedDate).ToShortDateString();
myArticle.ReceivedDate = prevDate;
}
else myArticle.ReceivedDate = "-";
}
Now, I am not a LINQ expert, if anyone can do the same code in the line where the DB is loaded in the List, I would appreciate it.
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;
I CanĀ“t get rowkey value displayed on gridview from Apache-Cassandra.
some of the code...
public class PacienteEntity
{
public int key { get; set; }
public string name { get; set; }
}
var records = (from x in context.ColumnList
where x.ColumnFamily == "paciente"
select x.ToObject<PacienteEntity>());
//remove null rows
var filteredRecords = records.ToList().Where(i => i != null);
dgView.DataSource = filteredRecords.ToList();
dgView.DataBind();
rowkey value is equal 0 even using autoGenerateColumns
Any help will be welcomed!
I basically pass the RowIndex via CommandArgument and use it to retrieve the DataKey value like
On the Button:
CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'
On the Server Event
int rowIndex = int.Parse(e.CommandArgument.ToString());
string val = (string)this.dgView.DataKeys[rowIndex]["myKey"];
You need to set Data Key Names in Gridview like below
<asp:gridview id="MyGridView"
datakeynames="Key"
onselectedindexchanged="MyGridView_SelectedIndexChanged"
runat="server">
Then in your event you can get the key as below
void MyGridView_SelectedIndexChanged(Object sender, EventArgs e)
{
int index = MyGridView.SelectedIndex;
var key =MyGridView.DataKeys[index].Value.ToString();
}
if you have already multiple keys like DataKeyNames="Key,Name"
You can now access each of DataKeys by providing its index like below:
string Key= MyGridView.DataKeys[index].Values[0].ToString();
string Name= MyGridView.DataKeys[index].Values[1].ToString();
Not sure about your DataSource binding, Please do as below, You need to map correct properties to set Key and Name in below code
var records = context.ColumnList.Where(x=> x.ColumnFamily == "paciente")
.Select(p=> new PacienteEntity(){ Key = p.P_Key, Name =p.P_Name}).ToList();
Sir/madam now my problem is this that I want to filter the Grid View of a page using a Drop Down list and a text box.
I mean to say like we write a SQL such as:
Select * from student where roll_no = 101;
Right,
Now I what that the column (roll_no in above statement) should be selected by the drop down list and the value (101 in the above statement) should be entered by the Text box.
In short I want to populate my grid view using Drop Down list and the value of text box by clicking a button..
For developing i am using dataset and table adapters.
Please, help me for this..
I use a drop-down list (combo-box) and a textbox to filter my DataGridView the following way and I think this is what you are looking for.
First, populate your DataGridView. You state you are using a DataSet and TableAdapters. I am guessing that you are using a BindingSource to tie your Data to your DataGridView. If that is the case, then you can Filter your data via the BindingSource.
My set up is similar to this:
My combobox contains the fields that I want to use in my Filter and the textbox is the value that I will be applying. The values in the combobox are user-friendly names so they will understand which field they are filtering on.
The code to apply the filter is:
private void ApplyFilter()
{
var filterEntered = FilterTextBox.Text.Trim().ToLower();
MyBindingSource.RemoveFilter(); // remove previous filter
string filterText = string.Empty;
string filterComboText = string.Empty;
switch (FilterComboBox.Text)
{
case "Profile":
filterComboText = "TSProfile"; // column name in the query
break;
case "User Id":
filterComboText = "TSUserId";
break;
case "Center":
filterComboText = "TSCenter";
break;
case "Prefix":
filterComboText = "TSPrefix";
break;
}
filterComboText = filterComboText + " = '";
filterText += (string.IsNullOrEmpty(filterComboText) ? string.Empty : filterComboText);
filterText += (!string.IsNullOrEmpty(filterText) && !string.IsNullOrEmpty(filterEntered) ? filterEntered + "'" : string.Empty);
MyBindingSource.Filter = filterText;
}
Basically what it is doing, is getting the text name of the combo-box and then the text in the textbox and applying the Filter to the BindingSource.
MSDN has an article on Filtering thats contains full sample code.
The one thing that I recommend is to provide the user with a way to easily remove the filter, I use a Remove Filter button.
it would be helpful if you showed us a little code first..
you could try something like this tho:
in your codebehind, add items to your dropdownlist.
List<yourObject> list = new List<yourObject>();
foreach (yourObject i in list)
{
DropdownList1.Items.Add(new ListItem("" i.name, "" + i.id));
}
im just giving an example here, i.name could be the name of a certain student, i.id would be the id associated with that given student.
Make sure you have the autopostback attribute of your dropdownlist set to true, like this:
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
Then in the selected Index Changed event of your dropdownlist, do the following:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
yourDataControl.DataSource = someMethod(Convert.toInt32(DropDownList1.SelectedValue));
yourDatacontrol.DataBind();
}
as i said, im not entirely sure what you're trying to do or how you're trying to do it.
the way i'm describing, you dont need the textbox to enter a certain value, by selecting an item in the dropdownlist you wil automatically get a value: in this case the ID associated with the selected item in the dropdownlist.
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.