I would like to know how I can access the edit and the update button from GridView?
I mean, if I click the edit button from the website in the GridView, I want to get some values from the tables.
For example: the button1 event.
Use a rowCommand on your button in template field
Check for your command name under rowCommand event
Open a database connection & execute SQL/stored procedure to fetch your records
Also if you use a SQLDataSource, it can automatically do it for you if you specify right queries.
You could make use of the GridView rowupdating event.
protected void myGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
The GridViewUpdateEventArgs contain properties for NewValues and OldValues.
I often use the following to cancel the update if nothing has actually been changed.
foreach (DictionaryEntry d in e.NewValues)
{
String oldValue = e.OldValues[d.Key] == null ? "" : e.OldValues[d.Key].ToString();
String newValue = d.Value == null ? "" : d.Value.ToString();
if (oldValue != newValue)
{
return; // -- change detected
}
}
e.Cancel = true; // -- don't execute the update
myGridView.EditIndex = -1;
Related
I am using the devexpress TreeList control. In Treelist I have a situation where one of my column is read only. This column may have some text values added when something happens in another cell. I have restricted user entry in the cell by setting a property like this
treeList1.Columns["col3"].OptionsColumn.ReadOnly = true;
Now I want to remove text value from some of the cells and since it is read only the delete buttons does not work. Can you suggest the event/method and the code which will allow user to delete the text?
Any help would be much appreciated.
Edited solution :
You should know that when the cursor is in the cell (in edit mode), and you press a button, it's not the TreeList who send the KeyDown event, but the RepositoryItemButtonEdit. So, you should handle the event also for the RepositoryItemButtonEdit.
To not duplicate code, I've wrote one handler 'onKeyDown', in whitch I verify who is the sender.
treeList1.KeyDown += onKeyDown;
riButtonEdit.KeyDown += onKeyDown;
And here is a code exemple showing you how to handle the KeyDown event for both treeList and repositoryButtonEdit, and set the cell value to null :
private void onKeyDown(object sender, KeyEventArgs e)
{
// Test if the button pressed is the delete button
if (e.KeyCode != Keys.Delete)
return;
// Test if the focused column is colValue
if (treeList1.FocusedColumn != colValue)
return;
// Set the cell value to null
treeList1.FocusedNode.SetValue(colValue, null);
// If it's the ButtonEdit who send the event, make it's EditValue null
var btnEdit = sender as ButtonEdit;
if (btnEdit != null)
{
btnEdit.EditValue = null;
}
}
what I need help with is: I have a field in the database (MySql) called seq_orcamento that allow null, when it is not null I need that a LinkButton inside a FormView(that has as datasource a SqlDataSource) to be visible. What I did in my select command is
SELECT CASE seq_orcamento WHEN NOT NULL THEN '1' ELSE '0' END AS idc_seq FROM log_transacao
It is working fine, but is there a way to do some kind of bind that when idc_seq = 1 the LinkButton becomes visible?
I have no problem using code-behind if any of it is necessary, I'm using C#
You can use DataBound event of FromView Control
protected void FormView1_DataBound(object sender, EventArgs e)
{
DataRowView dataRow = ((DataRowView)FormView1.DataItem);
LinkButton lb= (LinkButton )FormView1.FindControl("LinkButton ");
if (Convert.ToBool(DataBinder.Eval(formview.DataItem, "idc_seq") ) )
{ lb.visible=true; }
else{lb.visible=false;}
}
I found a way to do it: in the Visible propertie I added the code
Visible='<%# Eval("idc_seq") == "1" ? true : false %>'
Don't know if it works yet because I need to use it only when the site is published, I will try it later
I encountered a problem whereby when the user clicked on the delete button, Nothing happens and when I insert breakpoint to check, The selectLocStation is null. Why is it happening? Can anyone kindly solve my doubts about it?
Here are the codes for you to see my Delete codes. Appreciate any helps that were offered.
private void btnDel_Click(object sender, EventArgs e)
{
using (satsEntities Setupctx = new satsEntities())
{
int selectLocStation = Convert.ToInt32(cbLocStation.SelectedValue);
var DeleteRTiming =
(from delLocStation in Setupctx.requiredtimings
where delLocStation.RequiredLocationStationID == selectLocStation
select delLocStation).SingleOrDefault();
if (DeleteRTiming != null)
{
Setupctx.DeleteObject(DeleteRTiming);
Setupctx.SaveChanges();
cbLocStation.SelectedIndex = -1;
this.Edit_TS_Load(null, EventArgs.Empty);
MessageBox.Show("Selected Required Timing And " +
"The Location Station Has Been Deleted.");
}
}
}
This is the codes that were used to bind.
private void Edit_TS_Load(object sender, EventArgs e)
{
using (satsEntities Setupctx = new satsEntities())
{
var DeleteRT = (from DelRT in Setupctx.requiredtimings
join locationstationname ls in Setupctx.locationstationnames on DelRT.RequiredLocationStationID equals ls.locationstationID
select ls.locStatname).Distinct().ToList();
foreach (var locstationData in DeleteRT)
{
cbLocStation.Items.Add(locstationData);
}
}
}
How can selectLocStation be null ? it is of type int, are you getting any exception or you mean your object DeleteRTiming is null ? probably its the DeleteRTiming which is null
The simple answer to that the record you are looking in the database against selectLocStation is not there.
You need to put a break point and see what is being held by 'selectLocStation` and then check the database manually if the record exists in the database.
when you bind your control, you must set it in ! IsPostback and persist you with ViewState
If(! IsPostBack)
{
BindYourControl(); //For just first load.
}
Persist with
EnableViewState = true;
In order to don't erase your selected value
If this is a silverlight application then you might want to use
cbLocStation.SelectedItem
Or it is a ASP.Net site and you rebind the data on every pageLoad
Either way you should have an exception because you are trying to convert a null value.
See the method that you have used to bind the combo box
cbLocStation.Items.Add(locstationData);
This will create the combobox with "ValueField" and "TextFiled" with value of the variable "locstationData"
So when you try to get selected value from cbLocStation.SelectedValue ,it will always contain name and so you cannot parse it to integer.
There is another overload for the "Add" Which will accept Value(Id) and Text(Text to display)
cbLocStation.Items.Add(new ListItem(locstationData.locStatname, locstationData.locStatID));
Try to change the binding portion like this
I have 2 dropdownlists(ddl1,ddl2) and a gridview with 2 dropdown lists(gddl1,gddl2). On SelectedIndexChanged event of ddl1 am changing SelectedIndex of gddl1 in postback.
My problem is
ddl1.databind() occurs at a button's click event. So once selectedindex of ddl1 changes, the selected value losts and returns back to initial value.
I cant use !IsPostback because am binding ddl1 on button click.
How can I retain ddl1 and ddl2 selected index.?
protected void btnProceed_Click(object sender, EventArgs e)
{
if(ddlLocation.SelectedIndex > -1) {
empDS = ws_service.GetEmpList(ddlLocation.SelectedValue, ((ddlDept.SelectedValue == "All") ? "" : ddlDept.SelectedValue), ((ddlGrade.SelectedValue == "All") ? "" : ddlGrade.SelectedValue));
appraiserDS = ws_service.GetAppList();
grdDetails.DataSource = empDS.Tables[ 0 ].DefaultView;
grdDetails.DataBind();
ddlAppraiserAll.DataSource = appraiserDS.Tables[ 0 ].DefaultView;
ddlAppraiserAll.DataTextField = "APPRAISER_NAME";
ddlAppraiserAll.DataValueField = "APPRAISER_ID";
ddlAppraiserAll.DataBind();
}
}
protected void ddlAppraiserAll_SelectedIndexChanged(object sender, EventArgs e)
{
foreach(GridViewRow gvRow in grdDetails.Rows) {
Control ctrl = gvRow.FindControl("ddlAppraiserId");
DropDownList ddl = ctrl as DropDownList;
if(ddl != null)
ddl.SelectedIndex = ddlAppraiserAll.SelectedIndex;
}
}
The issue here is synchronization and its where you get it and where you bind it, but you can also direct get the value using the Request.Form.
Request.Form[DropDownListID.UniqueID]
I'm not sure if i understood your problem since it's difficult to see what's ddl1, ddl2, gddl1 and so on and when each event is handled.
But my guess is:
DataBind your GridView in btnProceed_Click
Bind the two DropDownLists of the GridView only in RowDataBound
Then your "GridView-DropDownLists" are always up-to-date according to the selected value of ddl1
you can retain ddl1 and ddl2 selected index by storing them in viewstate as properties.
private string ddlSelectedIndex
{
set { ViewState["SelectedIndex"] = value; }
get { return ViewState["SelectedIndex"] == null ? string.Empty : ViewState["SelectedIndex"].ToString(); }
}
The above property is in string, you can create an int property in similar way or use the same and cast index as string. Your selected index will be retained on subsequent postbacks.
I am making conditional formatting changes to the data in my gridview using a RowDataBound event:
void gvReg_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DateTime lastUpdate DateTime.Parse(DataBinder.Eval (e.Row.DataItem, "LAST_UPDATE");
if (lastUpdate < DateTime.Today.AddMonths(-1))
{
Hyperlink hypLastUpdate = (Hyperlink)e.Row.FindControl("hypLastUpdate";
hypLastUpdate.CssClass = "Error";
hypLastUpdate.NavigateUrl = "http://www.someExampleErrorPage.com";
}
}
}
This works, and sets the proper CssClass to the hyperlink (which makes it a jarring shade of bold red), but once the gridview is sorted (via the user clicking a column heading) the css class is reset on hypLastUpdate and it loses both it's style and associated NavigateUrl property.
The control hypLastUpdate is contained in a template field in a gridview, and it's text value is databound to a field called "LAST_UPDATE".
Is this a planned behavior (is sorting supposed to break the conditional formatting done in RowDataBound events?) or is there something I can check to make sure I am not doing something incorrectly?
I am not using the DataBind method anywhere in the code behind, and viewstate is turned on for the gridview in question.
--EDIT--
It ended up being a mistake in event handling.
I was doing:
gvReg.Sorted += {SomeEventHandler}
Inside of the page load event, but only when it wasn't a postback. This function called gvReg.DataBind after the grid view was sorted. I removed the handler wire up and instead added the event handler function to the OnSorted event. I guess assigned delegates to a gridview are not saved in ViewState between callbacks?
Hi here is a quick example of what I meant on my comment. This is the only way i could think of it:
protected void gvReg_Sorting(object sender, GridViewSortEventArgs e)
{
GridView gridView = (GridView)sender;
if (e.SortExpression.Length > 0)
{
foreach (DataControlField field in gridView.Columns)
{
if (field.SortExpression == e.SortExpression)
{
cellIndex = gridView.Columns.IndexOf(field);
break;
}
}
if (pSortExpression != e.SortExpression)
{
pSortDirection = SortDirection.Ascending;
}
else
{
pSortDirection = (pSortDirection == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending);
}
pSortExpression = e.SortExpression;
}
//Retrieve the table from the database
pSortOrder = pSortDirection == SortDirection.Ascending ? "ASC" : "DESC";
List<Partners> partnerList = GetPartnerList();
gvReg.DataSource = partnerList;
gvReg.DataBind();
}