I am unable to guess the issue here , as the event of grid item command is not executing .I also changes the pageevent validation state but of no use.
I am pasting .aspx code as well as
The grid is binded perfectly
<telerik:RadGrid ID="frds" runat="server" OnItemCommand="go_frd" AutoGenerateColumns="false" >
<MasterTableView>
<Columns>
<telerik:GridTemplateColumn>
<ItemTemplate>
<asp:Button ID="bt" runat="server" CommandArgument='<%#Eval("frd_ID") %>' Text="test" />
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
The event is this
protected void go_frd(object o, GridCommandEventArgs e)
{
if (e.CommandName == "frd_go")
{
Response.Redirect("Profiling.aspx?uid=" + e.CommandArgument);
}
if (e.CommandName == "add_frd")
{
db_accessDataContext db = new db_accessDataContext();
Frd_request req = new Frd_request();
db.AddFriend(Int64.Parse(cur_mem_id), Int64.Parse(e.CommandArgument.ToString()));
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("dbo.addFriend", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(#"memID", Int64.Parse(cur_mem_id));
cmd.Parameters.Add(#"frdID", Int64.Parse(e.CommandArgument.ToString()));
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex) { }
}
}
I tried many approaches but unable to fire the event for button in grid
I checked it by putting a break point as well ,the trouble is it don't even start execution of the event
Binding COde
string query = "my query containing the frd_id ,works fine in query builder and it also is shown grid view ";
try { SqlConnection con = new SqlConnection(connectionString);
SqlDataAdapter adapter = new SqlDataAdapter(query, con);
adapter.Fill(d0); con.Close();
} catch (Exception ex) { }
frds.DataSource = d0;
frds.DataBind();
You need to set the CommandName:
<asp:Button ID="bt" runat="server"
CommandName="frd_go"
CommandArgument='<%#Eval("frd_ID") %>' Text="test" />
I had a similar issue today.
In my radgrid I had the code to build the sql and populate the radgrid in the page_load event, but I forgot to add
if (!IsPostBack) { }
around this code, so on every page load the grid was being rebuilt and the onitemcommand method was not working. The page seemed to be was posting back on button click or rowclick, but the event was just not firing. Try adding the if (!isPostback) code around your databinding and you might find it works for you.
You will need to set EnablePostBackOnRowClick property to true for ClientSettings. However this will cause a full post back.
.
.
.
</MasterTableView>
<ClientSettings EnablePostBackOnRowClick="true">
</ClientSettings>
</telerik:RadGrid>
You may want to check this thread on Telerik forums
Related
I have a textbox and a label in ASP.NET and i want to automatically update the label with a value from database that is fetched using the content entered in textbox. This should be done dynamically when the text is changed in textbox and if a match if found in database, the corresponding value should be displayed in the label field (without page refresh). In this case I will enter employee ID in textbox and employee name should be displayed in label. I am using the following code,
<asp:ScriptManager ID="script_manager" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="update_name" runat="server">
<ContentTemplate>
<asp:TextBox ID="text_empID" TextMode="Number" MaxLength="6" AutoPostBack="true" OnTextChanged="text_empID_TextChanged" runat="server"></asp:TextBox>
<asp:Label ID="label_empName" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
The code behind is as follows,
protected void text_empID_TextChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select EmployeeName from EmployeeTable where EmployeeID=#id", con);
cmd.Parameters.AddWithValue("#id", text_empID.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
label_empName.Text = dt.Rows[0]["EmployeeName"].ToString();
}
}
But this is not working. Also after entering a value in textbox and if i click outside the box, the text inside disappears. Is there any other way to do this? or am i doing something wrong here?
I would suggest that you should add a button because the text_changed event only fires when the text-box blurs (loses focus).
That's a very weird behaviour and most users are not used to it and will not expect it.
<ContentTemplate>
<asp:TextBox ID="text_empID" TextMode="Number" MaxLength="6" runat="server></asp:TextBox>
<asp:button id="btnSearch" runat="server" OnClick="text_empID_TextChanged" />
<asp:Label ID="label_empName" runat="server"></asp:Label>
</ContentTemplate>
In any case, have you added a breakpoint? does the event fire? do you get any data back in the DataTable?
EDIT
After your last comment I am convinced that you are clearing the contents of the label on page load.
please, make sure that you only do that in the following context:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
label_empName.Text = "";
}
}
I'm displaying a datatable that selects a number of elements from the database (IncomingsId, Type, Cost, Frequency) and I'm not sure how to delete a row when a button is clicked.
I've tried many solutions so far but nothing is working.
Here is the button I have within my Grid view
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:button id="DeleteRowButton" text="Delete Record" onclick="DeleteRowButton_Click" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
And here is the code behind this page were I am creating the datatable.
SqlConnection con;
public _Default()
{
con = new SqlConnection(#"MySQLConnection");
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DisplayRecord();
}
}
public DataTable DisplayRecord()
{
string userId = (HttpContext.Current.User.Identity.GetUserId());
SqlDataAdapter Adp = new SqlDataAdapter("select * from Incomings where AspNetUsersId = '" + userId +"'", con);
DataTable Dt = new DataTable();
Dt.AcceptChanges();
Adp.Fill(Dt);
grid1.DataSource = Dt;
grid1.DataBind();
return Dt;
}
public void DeleteRowButton_Click(object sender, EventArgs e)
{
}
Cheers in advance for any help. I'm sure it's a simple resolution
You need a way for your code to know which ID to delete. Here is how I would normally do it:
Replace your button with an ItemTemplate, and add the button in here instead:
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button Text="Delete" runat="server" CommandArgument='<%# Eval("userId") %>' CommandName="Delete" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
When you have the button this way, you now have access to a CommandArgument and CommandName attributes. Notice the argument I am passing is Eval("userId"), the command name (as you will see later) is used to recognize what action you want to execute (this could be anything, is just a name).
Replace the CommandArgument with whatever value(s) you want to pass to the server, using the name that came from the database/datasource (I am guessing it would be userId).
Then, to capture this you need to implement the RowCommand event of the GridView, and intercept the correct CommandName:
public void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
string userId = e.CommandArgument.ToString();
//do something with the id
}
}
Here you have to make sure the CommandName in your button, matches to whatever action you want to execute in the RowCommand. This should do the trick.
Don't forget to bind the event to your GridView:
<asp:GridView OnRowCommand="GridView1_RowCommand" ID="GridView1" runat="server">
...
</asp:GridView>
just use this for the front-end code
<asp:GridView ID="grid1" OnRowDeleting="OnRowDeleting" DataKeyNames="deleteR" runat="server" AutoGenerateColumns="False" CellPadding="4" GridLines="None" style="width:100%" >
<columns>
<asp:TemplateField HeaderText="Delete Row">
<ItemTemplate>
<asp:Button ID="btnDelete" runat="server" class="btn btn-primary" Text="Delete" CommandName="Delete" OnRowDataBound="OnRowDataBound" />
</ItemTemplate>
</asp:TemplateField>
And have this in behind it:
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
int deleteR= Convert.ToInt32(grid1.DataKeys[e.RowIndex].Values[0]);
//have a sql statement here that add's the parameter ID for the row you want to delete, something like
SqlCommand com = new SqlCommand ("Delete FROM yourdatabase Where yourID = #yourID"
com.Parameters.AddWithValue("#yourID", yourID)
}
What you're looking for is indeed a simple solution.
You can use a foreach loop to search all DataRows within the DataTable for some kind of ID.Here's an example of what I mean:
String s = "/* IncomingsId for what you want to delete */";
foreach (DataRow r in dt.Rows) {
if (r["IncomingsId"].ToString().Equals(s)) {
dt.Rows.Remove(r);
}
}
Just a quick update for anyone that's helped me, thanks for your advice.
Asp.Net has it's own built in AutoGenerateDeleteButton and I set that to true and ran a bit of code behind it.
A simple solution that really shouldn't have taken me all day to complete!
Dear Stack Overflowers,
I have a gridview in the front end page and here it is in asp.net code:
<asp:GridView ID="grdManufact" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#336666" BorderStyle="Double" BorderWidth="3px" CellPadding="4"
GridLines="Horizontal" AllowPaging="True" OnRowDataBound="manufGridView_RowDataBound" EnableModelValidation="False" EnableSortingAndPagingCallbacks="True" HorizontalAlign="Center" OnSelectedIndexChanged="grdManufact_SelectedIndexChanged" OnPageIndexChanging="grdManufact_PageIndexChanging">
<Columns>
<asp:BoundField DataField="SrNo" HeaderText="SrNo" />
<asp:BoundField DataField="Manufacturer" HeaderText="Manufacturer" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:BoundField DataField="isModerated" HeaderText="Approved" />
<asp:BoundField />
Well that is the main part of it but it displays correctly and binds correctly upon page load.
Whenever I change page to page 2 or 3 or whatever of the gridview, my gridview disappears! I have tried putting a breakpoint in the PageIndexChanging function but the breakpoint is not reached which tells me that the event is not even firing and yet the gridview just disappears. Here is my backend function Page Index Changing anyway:
protected void grdManufact_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdManufact.PageIndex = e.NewPageIndex;
BindGrid();
}
And the BindGrid() function used to bind the grid :
public void BindGrid()
{
string strConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString2"].ToString();
SqlConnection conn = new SqlConnection(strConnectionString); // Connect to database
conn.Open(); // Open Connection
string com = "select ManufacturerID as SrNo, ManufacturerName as Manufacturer, ManufacturerDescription as Description,isModerated From VehicleManufacturer";
SqlDataAdapter adpt = new SqlDataAdapter(com, conn); // Select all manufacturers in the table
DataTable dt = new DataTable(); // Create a new Data Table
adpt.Fill(dt); // Fill it with manufacturers
grdManufact.DataSource = dt; // Make the datasource of the manufacturer grid the new table
grdManufact.DataBind(); // Bind data for the grid
conn.Close(); // Close database connection. Disconnect
}
Here is my page load in case you wanted that too:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) // If this is the first time loading the page through postback
BindGrid(); // Bind the Manufacturers to the gridview
else
{
ClientScript.GetPostBackEventReference(this, string.Empty);
if (Request.Form["__EVENTTARGET"] == "Button2_Click")
{
//call the method
btnDelete_Click(this, new EventArgs());
}
}
}
Can you please tell me what I am doing wrong or point me in the right direction to fix this please?
remove EnableSortingAndPagingCallbacks="True" property if you need to excute server side page index changed event or set it false
I remember that this happen if you set EnableViewState = false. Make it EnableViewState = true ! If the grid disappears on every postback just put the binding in if(!IsPostBack) in Page_Load method.
I am using VS2005. Currently I have a delete linkButton in my gridview, and if I presses on it to delete a row, the GridView goes empty, and I will have to click on the link again to access the page.
Below is my codefor .aspx:
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" ondatabound="gv_DataBound" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="UserSelection" OnCheckedChanged="UserSelector_CheckedChanged" runat="server" />
<asp:LinkButton ID="lnkDelete" runat="server" onclick="lnkDelete_Click" Text="Delete" CommandArgument='<%# Eval("Employee") %>' ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Below is my code for .cs
protected void lnkDelete_Click(object sender, EventArgs e)
{
LinkButton lnk = (LinkButton)sender;
string stid = lnk.CommandArgument.ToString();
SqlDataSource1.SelectCommand = "DELETE FROM [UserDB]where Employee like '%"+stid+"%'";
SqlDataSource1.DataBind();
}
I have tried assigning my delete query to SqlDataSource1 and select query to source2, but if that's the case, my delete query would not work.
I have also tried using IsPostBack on my PageLoad method, but the GridView goes empty as well after clicking on the delete button.
Currently both of my queries are assigned to SqlDataSource1, and once the query is deleted, the page just go blank, although the query is deleted.
May I know how can I refresh the page or reload the GridView table after the delete query is ran?
Thank you.
Thanks to the help from you guys, the problem is solved. Currently my working code is as follows:
LinkButton lnk = (LinkButton)sender;
string stid = lnk.CommandArgument.ToString();
SqlConnection conn = new SqlConnection("DATA-SOURCE");
string sql = string.Format("DELETE FROM [UserDB] where Employee like '%{0}%'",stid);
SqlCommand cmd = new SqlCommand(sql,conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
SqlDataSource1.SelectCommand = "SELECT * FROM [UserDB]";
SqlDataSource1.DataBind();
Response.Redirect("/Project/UserList.aspx");
I used a sql connection string for the delete query, and sqldatasource for the select query afterwards, finally refreshed the page by using response.redirect. Hope it helped newbies like me who met this error too.
Great thanks to all who provided help
Why are you assigning a DELETE command to the SelectCommand property ?
Just run the DELETE on a separate SqlCommand instance with ExecuteNonQuery and commit. Another option is to use DeleteCommand of the existing SqlDataSource.
Another point:
The way you build the DELETE SQL is vulnerable to a serious security problem called SQL injection - easiest and best way to avoid that is to use bind parameters!
First you should read up on what databinding in ASP.NET can do for you. (Then you won't have to write any codebehind for this scenario.)
Example: (Not tested in VS)
You should use the SqlDataSource's DeleteCommand to set the delete command and its parameters like this:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="..."
SelectCommand="..."
DeleteCommand="DELETE FROM [UserDB] WHERE Employee=#Employee">
<DeleteParameters>
<asp:Parameter Name="Employee" />
</DeleteParameters>
</asp:SqlDataSource>
And the on the GridView, you should set the DataKeyNames property, and inside the ItemTemplate's Linkbutton you should set the CommandName property to "Delete" as shown below:
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1"
ondatabound="gv_DataBound" DataKeyNames="Employee"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="UserSelection" runat="server"
OnCheckedChanged="UserSelector_CheckedChanged" />
<asp:LinkButton ID="lnkDelete" runat="server"
onclick="lnkDelete_Click" Text="Delete"
CommandArgument='<%# Eval("Employee") %>'
CommandName="Delete" ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Try like this
protected void lnkDelete_Click(object sender, EventArgs e)
{
LinkButton lnk = (LinkButton)sender;
string stid = lnk.CommandArgument.ToString();
SqlConnection conn = new SqlConnection(<put your connectionstring here>);
string sql = string.Format("DELETE FROM [UserDB] where Employee like '%{0}%'",stid);
SqlCommand cmd = new SqlCommand(sql,conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
BindTheGridView();
//or you can use SelectCommand of your SqlDataSource1 and can bind again simply.
}
EDIT:
public void BindTheGridView()
{
SqlConnection conn = new SqlConnection(Connstring);
string sql = "Select * from [UserDB]";
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dtb = new DataTable();
da.Fill(dtb);
conn.Close();
SqlDataSource1.DataSource = dtb;
SqlDataSource1.DataBind();
}
And you can call this for any time to bind the values.
It's wrong to run change operation (DELETE in your example) as a SelectCommand. SelectCommand must be used as it called - only to SELECTs.
Run the DELETE query separately, then run a SELECT command to show the relevant records for the grid.
SqlDataSource1.SelectCommand = "DELETE FROM [UserDB]where Employee like '%"+stid+"%'";
SqlDataSource1.DataBind();
Why are you using Delete query in SelectCommand. The query is open to SqlInjection attack. I would have used a stored procedure and verify the parameter before passing it to the procedure.
Moreover the Grid won't show/bind any data as your code is not return any data back. It is just deleting the data.
I guess you can do a gridview.DataBind() instead of sqlDatasource.databind. The gridviews databind internally performs the sqldatasource databind and also refreshes the gridview.
I have a LinkButton which fires an OnClick event to update some Labels; however, after the first firing of OnClick, it won't fire again when I click another (or the same) LinkButton which runs the same OnClick event. (It's a list of people, each a LinkButton, and clicking on one brings up their details)
If I leave the page a few minutes, it will work again, almost as if whatever was preventing OnClick firing timed-out. Of course, this won't be any use to the users!
This is my ASP.NET code for the LinkButtons (encapsulated in a DataList):
<asp:DataList ID="DataList1" runat="server" DataKeyField="AdmissionNumber">
<ItemTemplate>
<asp:CheckBox ID="CheckBox" runat="server" OnCheckedChanged="Checkbox_CheckedChanged" ViewState="true"/>
<asp:LinkButton ID="LinkButton" runat="server" OnClick="LinkButton_OnClick">
<asp:HiddenField ID="hfAdmissionNumber" Value='<%# Eval("AdmissionNumber") %>' runat="server"/>
<asp:Label ID="CalledLabel" runat="server" Text='<%# Eval("Called") %>' />
<asp:Label ID="SurnameLabel" runat="server" Text='<%# Eval("Surname") %>' />
</asp:LinkButton><br /><br />
</ItemTemplate>
</asp:DataList>
In the Page_Load event in the C# code behind, the following populates the DataList:
connection.Open();
SqlDataReader reader = command.ExecuteReader();
DataList1.DataSource = reader;
DataList1.DataBind();
connection.Close();
And this is the OnClick event:
protected void LinkButton_OnClick(object sender, EventArgs e)
{
LinkButton l = (LinkButton)sender;
HiddenField hfv = (HiddenField)l.Parent.FindControl("hfAdmissionNumber");
using (SqlConnection connection = new SqlConnection("Data Source=pastonmis01\\inform;Initial Catalog=2009;Integrated Security=True"))
{
using (SqlCommand command = new SqlCommand("xProcSportNotParticipantDetails",connection))
{
connection.Open( );
command.CommandType = System.Data.CommandType.StoredProcedure;
command.Parameters.AddWithValue("#AdmissionNumber", Int32.Parse(hfv.Value));
SqlDataReader reader = command.ExecuteReader();
reader.Read();
lTitle.Text = reader.GetValue(0).ToString();
lSurname.Text = reader.GetValue(1).ToString();
lForename.Text = reader.GetValue(2).ToString();
lCalled.Text = reader.GetValue(3).ToString();
lDoB.Text = reader.GetValue(4).ToString().Substring(0,10);
lSex.Text = reader.GetValue(5).ToString();
reader.Close();
}
connection.Close();
}
}
All the connections work, the data is retrieved, etc, so everything except the OnClick firing works. I've done a search of the internet and found this seems to have been a long-standing problem since the first ASP.NET, but there is no solution for ASP.NET 3.5. Does anyone know what causes this, or where I might be going wrong?
Try giving OnClientClick="Page_BlockSubmit=false" for your link button