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();
Related
I am auto generating columns in gridview depending on search parameters, few columns will be added or removed.
Please suggest me a way to set the date format to dd-mmm-yyyy for entire column in gridview.
For now, I'm doing it using rowdatabound. It checks every row, So it takes time to show the results.
This is what I do in rowdatabound
if (e.Row.RowType == DataControlRowType.DataRow)
{
System.Data.DataRowView dtview;
DateTime dt;
int intCounter;
dtview = (DataRowView)e.Row.DataItem;
for (intCounter = 0; intCounter <= dtview.Row.ItemArray.Length - 1; intCounter++)
{
if (dtview.Row.ItemArray[intCounter] is System.DateTime)
{
dt = (DateTime)dtview.Row.ItemArray[intCounter];
e.Row.Cells[intCounter].Text = dt.ToString("dd-MMM-yyyy");
}
}
}
This checks for all records and then changes based on condition.
But I want to do it better, just by identifying the column and change the date format for complete column.
Disclaimer: I haven't tried this myself, but it looks possible.
A GridView has a public property called ColumnsGenerator that has a type of IAutoFieldGenerator. This is the object that determines how the columns are generated.
There's already an implementation of IAutoFieldGenerator out there, the default one: GridViewColumnsGenerator. This is a public, non-sealed class, and you can derive a type from it.
The method you would have to override is this one:
public override List<AutoGeneratedField> CreateAutoGeneratedFields(
object dataObject, Control control);
Note the output, a List<T> of AutoGeneratedField. AutoGeneratedField has a property called DataFormatString:
public override string DataFormatString { get; set; }
So all you'd have to do is override CreateAutoGeneratedFields, like this:
public class MyDerivedGridViewColumnsGenerator : GridViewColumnsGenerator
{
public override List<AutoGeneratedField> CreateAutoGeneratedFields(
object dataObject, Control control)
{
var list = base.CreatedAutoGeneratedFields(dataObject, control);
foreach(var field in list)
{
if(field.DataType == typeof(DateTime))
field.DataFormatString = "dd-MMM-yyyy";
}
return list;
}
}
Now, I'm not clear on how the ColumnsGenerator property gets set, so you might have to do it in code. But that should be fairly simple, since GridViewColumnsGenerator has a parameterless constructor:
// GridView myGridView;
myGridView.ColumnsGenerator = new MyDerivedGridViewColumnsGenerator();
I would set it before you bind to the GridView, so it's in place when it's time to create the columns.
I'm a little late. But this worked for me. It still uses the RowDataBound() method. But it only runs against the first row in the data source.
protected void gvGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
DataRowView drv = (DataRowView)e.Row.DataItem;
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int i = 0; i < ct_columns; i++)
{
DataControlFieldCell dcf = e.Row.Cells[i] as DataControlFieldCell;
/* default date format: hide 'time' values */
if (e.Row.RowIndex == 0
&& (dcf.ContainingField.GetType().Name == "BoundField" // defined columns
|| dcf.ContainingField.GetType().Name == "AutoGeneratedField")) // auto-generated columns
{
BoundField bf = dcf.ContainingField as BoundField;
if (bf != null && String.IsNullOrEmpty(bf.DataFormatString))
{
string col_name = bf.DataField;
if (!String.IsNullOrEmpty(col_name) && drv[col_name] != null)
{
if (drv[col_name].GetType().Name == "DateTime")
{
// set format for first row
string date = drv[col_name].ToString();
if (!String.IsNullOrEmpty(date))
dcf.Text = DateTime.Parse(date).ToShortDateString();
// set format for other rows
bf.DataFormatString = "{0:M/dd/yyyy}";
}
}
}
}
}
}
}
if you are binding an DataTable to Grid then Write an extension method or link Query like
public static void ChangeDateFormat<T>(this DataColumn column, Func<object, T> conversion)
{
foreach(DataRow row in column.Table.Rows)
{
row[column] = conversion(row[column]);
}
}
And to call that Method
dataTable.Columns["DateColumanName"].ChangeDateFormat(
val => DateTime.Parse(val.ToString()).ToString("dd/MMM/yyyy"));
Actual Source code pulled from here
And also note you need check the existence of column and data type and the other checks to get rid of errors.
Hope it helps.
Here's a fairly simple solution: rather than handle each row separately, set-up the columns before binding the grid.
In the following example, view is an object that generates a regular DataTable and the grid view has its AutoGenerateColumns property set to false.
Essentially, you just examine the columns' data type and when its a DateTime, set the format you want.
DataTable dt = view.GetReport();
Type dateType = typeof(DateTime);
foreach (DataColumn column in dt.Columns)
{
BoundField f = new BoundField();
f.HeaderText = column.ColumnName;
f.DataField = column.ColumnName;
if(column.DataType == dateType)
f.DataFormatString = "{0:d}"; // Or whatever
gvReport.Columns.Add(f);
}
gvReport.DataSource = dt;
gvReport.DataBind();
I managed to format the values of an auto generated datetime column implementing the event ColumnAdded of the DataGridView:
private void dataGridView_ColumnAdded(object sender, DataGridViewColumnEventArgs e)
{
if (e.Column.ValueType == typeof(DateTime))
{
e.Column.DefaultCellStyle.Format = "dd-MMM-yyyy";
}
}
Use Eval function to define string formation in aspx code:
<% # Eval("Date", "{0:dd-MMM-yyyy}") %>
Complete Example:
<asp:TemplateField HeaderText="Date">
<ItemTemplate>
<% # Eval("Date", "{0:dd-MMM-yyyy}") %>
</ItemTemplate>
</asp:TemplateField>
I use entity Framework to connect to a database and retrieve some information from a table. I need to show this information in a drop down list. I need to set each list Item value equals to the Id which sets in database.
public void EducationDropDownListViewer()
{
EducationDropdown.Items.Add(new ListItem { Text = "--select--", Value = "0" });
List<Education> educations = ModelLists.GetEducationList();
for (int i = 0; i < educations.Count; i++)
{
ListItem educationListItem = new ListItem();
Education education = educations[i];
educationListItem.Text = education.EducationName;
educationListItem.Value = education.Id.ToString(CultureInfo.InvariantCulture);
EducationDropdown.Items.Add(educationListItem);
}
}
I expect the Id sets corresponding to each row's Id from DB, But It will set serially starts by 1. How I can set this property to correct value? I need to use this value which selects through this code to do some updates in database tables.
protected void EducationDropdown_SelectedIndexChanged(object sender, EventArgs e)
{
ViewState["educationid"] = Convert.ToInt32(EducationDropdown.SelectedIndex);
}
SelectedIndex property return the progressive Index of the current select item in the whole DropDownList.
You are looking for the SelectedValue property that returns the Value of the SelectedItem
protected void EducationDropdown_SelectedIndexChanged(object sender, EventArgs e)
{
// If you accept also the item at index zero (the prompt to select) then change
// the test below to >=
if(EducationDropDown.SelectedIndex > 0)
ViewState["educationid"] = Convert.ToInt32(EducationDropdown.SelectedValue);
}
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
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 have a grid view that looks like this for example :
I need to delete the selected row where there is a hidden column activityID and taskID which I set visible to false because I need their value to delete it from the database.
So here is my code:
protected void gvQuestion_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "delete")
{
Model.question del = new Model.question(); // Entitiy CRUD
del.ActivityID = Convert.ToInt32(gvQuestion.Rows[0].Cells[2].ToString()); // Value of ActivityID column in GV
del.TaskID = Convert.ToInt32(gvQuestion.Rows[0].Cells[3].ToString()); // Value of TaskID column in GV
daoQuestion.Delete(del);
}
daoQuestion.Save();
}
protected void gvQuestion_RowDeleted(object sender, GridViewDeletedEventArgs e)
{
e.ExceptionHandled = true;
}
I followed the guide here : http://www.codeproject.com/Articles/111037/Delete-Data-in-GridView-Using-Template-Button
But I am using the entity framework to delete, however I get the error of System.FormatException: Input string was not in a correct format., and the error lies in the delete statement. I searched for the error, and it says it might be a null value. How do I solve this problem?
Btw , i populated this grid view from Database as well.
var itemToDel = context.Questions.FirstOrDefault(q=>q.ActivityID = aid && q.TaskID == tid);
if(itemToDel !=null){
context.Questions.DeleteObject(itemToDel);
context.SaveChanges();
}
To Get values from current deleting row, try below
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gvQuestion.Rows[index];
var aid = Convert.ToInt32(row.Cells[2].Text);
var tid = Convert.ToInt32(row.Cells[3].Text);
I think you need to query the model first like the one below. Im not too familliar with linq, just correct the syntax if wrong.
Model.question del = new Model.question();
var item = from d in del
where d.ActivityID == Convert.ToInt32(gvQuestion.Rows[0].Cells[2].ToString());
and d.TaskID == Convert.ToInt32(gvQuestion.Rows[0].Cells[3].ToString());
select d;
daoQuestion.Delete(item);
I think your conversion is the culprit, that is, the values of your cells are converted to Int32 and if it empty by the way it will give the error "Input String was not in correct format". So, this one below is potential for error:
del.ActivityID = Convert.ToInt32(gvQuestion.Rows[0].Cells[2].Text);
del.TaskID = Convert.ToInt32(gvQuestion.Rows[0].Cells[3].Text);
So, why not use TryParse instead and check if there is value first like:
if (e.CommandName == "delete")
{
int ActID, TskID;
Int32.TryParse(gvQuestion.Rows[0].Cells[2].Text, out ActID);
Int32.TryParse(gvQuestion.Rows[0].Cells[3].Text, out TskID);
// Try to Debug here to show the value of ActID and TskID if you have the right values.
if (ActID>0 && TskID > 0)
{
Model.question del = new Model.question(); // Entitiy CRUD
del.ActivityID = ActID; // Value of ActivityID column in GV
del.TaskID = TskID; // Value of TaskID column in GV
daoQuestion.Delete(del);
}
}
Try also DataKeys instead of Rows[].Cells[] like:
gvQuestion.DataKeys(e.EditIndex).Item("ActivityID");
gvQuestion.DataKeys(e.EditIndex).Item("TaskID");
Or:
gvQuestion.DataKeys[0].Values[2];
gvQuestion.DataKeys[0].Values[3];
See sample links here and here for reference
Check the DataKeyNames="Id" in the Gridview is set to Question ID and for deleting use the following code,
protected void grid_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.ToUpper().ToString() == "DELETE")
{
ViewState["id"] = e.CommandArgument.ToString().Trim();
Model.question del = new Model.question();
del.ActivityID = Convert.ToInt32(gvQuesViewState["id"]).ToString());
del.TaskID = Convert.ToInt32(ViewState["id"]).ToString());
daoQuestion.Delete(del);
}
daoQuestion.Save();
}