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
Related
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 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;
I have a gridview that has a list of Salesman names. When a Salesman is selected using A ButtonFieldTemplate in the Grid. I need the name of selected Salesman to appear in a Label.
So far I have this but it is not working:
protected void gvSalesmanByManager_SelectedIndexChanged(object sender, EventArgs e)
{
lblSalesmanCustomers.Text = gvSalesmanByManager.SelectedValue + "'s Customers";
}
It's not throwing any errors. Not even red squiggly lines in Visual Studio. It's just plain not working.
How can I accomplish this in ASP.net and C# 4.0.
Regarding to the documentation SelectedValue gets the data key value of the selected row in a GridView control. Does your GridView contain a column with the key and did you set the dataKeyNamesProperty (such as datakeynames="myID")?
EDIT:
To access a value of a column you can use SelectedRow:
GridViewRow row = GridView1.SelectedRow;
lblSalesmanCustomers.Text = row.Cells[2].Text;
EDIT2:
There are two options when you want to read the template field. Either you store your value in an additional invisible column or you access the controls inside the template field. Something like this should work:
lblSalesmanCustomers.Text = ((TextBox)row.Cells[2].FindContol("tbxName")).Text;
Make sure you are not assigning empty text on page load event.
or you need to place those initialization in if(!Page.IsPostback) block
My code so far : protected void gvSalesmanByManager_SelectedIndexChanged(object sender, EventArgs e) { lblSalesmanCustomers.Text = gvSalesmanByManager.SelectedValue + "'s Customers"; } –
try in the event "gvSalesmanByManager_SelectedIndexChanged" following code:
lblSalesmanCustomers.Text = gvSalesmanByManager.SelectedRow.Cells[0].Text;
You said something about a "ButtonFieldTemplate" please show me some code from your ascx-file this will help us much i think.
*Edit:
"Controls[1]" has not to be right. But 0 is a literal. you could also debug your code and set breakpoints. would be much easier.
try this with Linkbutton:
LinkButton lnk1 = gvSalesmanByManager.SelectedRow.Cells[0].Controls[1] as LinkButton;
lblSalesmanCustomers.Text = lnk1.Text;
best regards,
noone
I have at the moment a problem with RowUpdating from a GridView and accessing the new values. I add a dynamic DataTable to my GridView.DataSource and bind to it. If I use the update button nothing happens and I get back to my normal GridView.
Here's my Page_Load event:
protected void Page_Load(object sender, EventArgs e)
{
Control test = GetPostBackControl(Page);
if (Page.IsPostBack)
{
if ((test.ID == "SumbitSearch") && (DropDownListFrom.Text != "") && (DropDownListTo.Text != "") && (SearchField.Text != ""))
{
DataTable result = new DataTable();
string from = null;
string to = null;
switch (DropDownListFrom.SelectedIndex)
{
case 0:
from = DropDownListFrom.Items[0].Value;
break;
case 1:
from = DropDownListFrom.Items[1].Value;
break;
case 2:
from = DropDownListFrom.Items[2].Value;
break;
}
switch (DropDownListTo.SelectedIndex)
{
case 0:
to = DropDownListTo.Items[0].Value;
break;
case 1:
to = DropDownListTo.Items[1].Value;
break;
case 2:
to = DropDownListTo.Items[2].Value;
break;
}
result = LoadGridView(from, to);
GridViewResult.DataSource = result;
Session["Result"] = result;
GridViewResult.DataBind();
GridViewResult.Columns[0].Visible = true;
GridViewResult.Columns[1].Visible = true;
GridViewResult.HeaderRow.Cells[0].Width = Unit.Pixel(110);
GridViewResult.HeaderRow.Cells[1].Width = Unit.Pixel(60);
GridViewResult.HeaderRow.Cells[3].Text = "Nach: " + from;
GridViewResult.HeaderRow.Cells[4].Text = "Von: " + to;
}
}
else
{
GridViewResult.DataBind();
}
}
Later, the GridView should only appear if both DropDownLists are used and the SearchField is not empty. I also check if the button which execute the PostBack is the search button.
Here is what I added to the RowUpdating EventHandler:
protected void TaskGridViewResult_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewResult.DataSource = (DataTable)Session["Result"];
for (int i = 0; i < GridViewResult.Columns.Count; i++)
{
DataControlFieldCell cell = GridViewResult.Rows[e.RowIndex].Cells[i] as DataControlFieldCell;
GridViewResult.Columns[i].ExtractValuesFromCell(e.NewValues, cell, DataControlRowState.Edit, true);
}
GridViewResult.EditIndex = -1;
DataBind();
}
What is going wrong?
Last Change: More Information (#jwiscarson)
I’m sorry, I was in hurry. I will try to give you a better view.
In that project, the users could select 2 categories, enter a search string and the result will show in a GridView. The RowUpdating stuff is for the "admin user".
Here is my problem, if the "admin user" click on edit, change the value of the cell and execute the update, the value would not changed in the DataTable.
Without seeing your markup, it's hard for […] based on some search
criteria?
I add GridViewResult as markup in my project.
I'm also not sure why […] within that button's Click event.
Yes, I thought that too! But I read in a blog it is better to put the code into Page_Load(), if you are working with GridViews. I believed him. Is it okay, to put that code into the click event handler from my button? I'm very new to that. I just could read lots of blogs, msdn and ask here.
TaskGridViewResult_RowUpdating is also added as markup to my code. Could I also create this and the GridView in my CreateChildControls()?
As markups I have two DropDownLists, a TextBox for the search string, a search submit Button and the GridView.
At the moment, i havent the exactly code here but the GridView looks like:
<asp:GridView ID="GridView1" runat="server"
OnRowUpdating="TaskGridViewResult_RowUpdating">
<!-- // More of that... -->
<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:GridView>
I could give you more details tomorrow.
Maybe I forgot this. Before I could click the update button and execute the TaskGridViewResult_RowUpdating event to change the value of the cell. I set the row editable with:
protected void TaskGridViewResult _RowEditing(object sender, GridViewEditEventArgs e)
{
GridViewResult.EditIndex = e.NewEditIndex;
DataBind();
}
Next Change:
I added to the GridView few TemplateFields like:
<asp:TemplateField HeaderText="test">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("from") %>'> </asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("from") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
This is it, I have access to the new value with:
string test = ((TextBox)row.FindControl("TextBox1")).Text;
in TaskGridViewResult_RowUpdating()
Now, I just have to bind the template dynamically with the values from the dropdown list, and that’s it I think.
Thanks!
Hoo boy.
You didn't ask this in your question, but you've written some smelly code here. I'll try to address your question, but I'm also going through some of the other problems here.
Without seeing your markup, it's hard for me to tell if you've created GridViewResult programmatically or if it's in your markup as well. I'm not exactly sure what TaskGridViewResult is either -- is this an event for GridViewResult? Do you have another GridView on your page, and you want to show GridViewResult based on some search criteria?
I'm also not sure why you put all of your GridView binding code in Page_Load. I see that you're checking GetPostBackControl to find the control that caused the PostBack -- this is a code smell. If your users have to click a specific "Search" button, you should isolate your GridView binding code within that button's Click event.
Anyway, as to TaskGridViewResult_RowUpdating:
It looks like you're trying to update GridViewResult's old values to the new values by setting its DataSource and then iterating through its data. You can't do that. What happens when you change your RowUpdating event to:
protected void TaskGridViewResult_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewResult.DataSource = (DataTable)Session["Result"];
GridViewResult.DataBind();
}
Now, other asides:
Your switch statements are code smells. DropDownLists expose a property called SelectedValue -- if you have some default value that isn't a valid selection (like the first option in your DropDownList), then you can change your original code from:
if ((test.ID == "SumbitSearch") && (DropDownListFrom.Text != "") && (DropDownListTo.Text != "") && (SearchField.Text != ""))
{
string from = string.Empty;
string to = string.Empty;
switch (DropDownListFrom.SelectedIndex)
{
case 0:
from = DropDownListFrom.Items[0].Value;
break;
/* other cases */
}
switch (DropDownListTo.SelectedIndex)
{
case 0:
to = DropDownListTo.Items[0].Value;
break;
/* other cases */
}
/* snip */
}
to:
if (test.ID == "SubmitSearch" && DropDownListFrom.SelectedIndex > 0 && DropDownListTo.SelectedIndex > 0 && SearchField.Text != "")
{
string from = DropDownListFrom.SelectedValue;
string to = DropDownListTo.SelectedValue;
/* snip */
}
If you can, please post your markup. I can offer you some more specific help or advice if I can tell what Controls you have on your page, and how they interact.
Edit: I should also add that you should get in the habit of using String.IsNullOrEmpty(string variable), rather than comparing to "". Although this isn't as big of a problem when you're referencing the text from web controls, getting in the habit now will prevent you from serious headaches and inefficiently checking for null and empty later. If you're in .NET 4.0, you should have access to IsNullOrWhiteSpace(), which is (in my opinion) more useful on the web, where users are more likely to try to enter junk data.
Edit 2: In response to your additional details above:
In your RowUpdating event, you need to pull the new values out of the front-end controls, and then re-bind your data. It looks like your source code is pretty close to the MSDN source code here. The difference between your code and the code on MSDN is:
- The MSDN code takes the new data from the edited row and updates the appropriate data in the Session variable with that new data.
- The MSDN code has a BindData() function -- I'm not sure if this is what your DataBind() function is, however.
- The MSDN code updates the GridView by re-binding the GridView to the appropriate data in the Session.
Frankly, I have some issues with the MSDN code. I really, really hate seeing code like: dt.Rows[row.DataItemIndex]["Id"] = ((TextBox)(row.Cells[1].Controls[0])).Text; To me, this is garbage, because it's so highly coupled to the order of your cells.
If I had written the code, I would explicitly create all the front-end controls and use a binding command (if you aren't familiar, it looks like <%# DataBinder.GetPropertyValue(Container.DataItem, "FieldName") %> in the markup -- see more details here). Then, in my RowUpdating event, I'd use e.Row.FindControl("controlName"), and update the Session data from that.
Honestly, if your back-end data isn't changing on a regular basis, I don't see any reason to programmatically create your GridViews. It over-complicates your C# code to go through these steps yourself when you can just set it up once in your markup. If you need to hide one GridView, you can always set its Visible property to false. Then, when you're ready to show it, set Visible = true.
Finally, I've spread my GridView code across so many events (button clicks, RowDataBound events from other GridViews/Repeaters, etc.), I can't imagine why someone would suggest that you only put it in Page_Load.
I am trying to obtain the ctl property that is specific to each row in a gridview. In my scenario, there is a list of titles, each title is displayed as a hyperlink using the LinkButton. When this is clicked, I would like to pass the ctl property (or what ever value is specific to that title, to the database and pull the information that is relative to the value).
I guess my first step is to obtain the ctl value. Could someone please help me get on my way. Thanks in advance.
You will need to keep track of the control ID that is written to the page in the row created event. Make a integer to increment for each row written and save it as a command argument on a link in the grid.
linkbutton CommandArgument='<%# Eval("some_id") %>'
protected void linkButton_Click(object sender, EventArgs e)
{
LinkButton linkButton = (LinkButton) sender;
if (linkButton != null)
{
if (linkButton.CommandArgument != null)
{
...some code...
}
}
}