I have the below gridview on a page to display users with a role of "Reviewer". The grid pulls up the records correctly. On the gridview is a "delete" button to remove the Reviewer role. The stored procedure that is called is working correctly when ran manually, but I seem to be missing something on the aspx or codebehind page as while no error is returned, no record is deleted either.
aspx control for gridview:
<asp:GridView ID="GridView1" runat="server" Caption="Current Reviewers" AllowSorting="True" PagerSettings-Mode="NumericFirstLast" OnPageIndexChanging="GridView1_PageIndexChanging"
CaptionAlign="Top" EmptyDataText="No Reviewers Configured." PageSize="10" AllowPaging="true" PagerStyle-HorizontalAlign="Center" PagerStyle-Font-Size="Large"
AutoGenerateColumns="false" AlternatingRowStyle-BackColor="#cccccc" DataKeyNames="UserId" OnRowDeleting="DeleteRecord">
<Columns>
<asp:BoundField DataField="UserId" HeaderText="Id" ItemStyle-Width="300" />
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="250" />
<asp:TemplateField HeaderText="Delete?">
<ItemTemplate>
<span onclick="return confirm('Are you sure to Delete the record?')">
<asp:LinkButton ID="lnkB" runat="Server" Text="Delete" CommandArgument='<%# Eval("UserId") %>' CommandName="DeleteRecord"></asp:LinkButton>
</span>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Updated with full code behind:
namespace cs1.Admin
{
public partial class ReviewerMaintenance : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDownList1();
}
}
private void BindDropDownList1()
{
string connectionString = WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
string selectSQL = String.Format("SELECT Id as UserId, FirstName + ' ' + LastName As Name from AspNetUsers where Id in(SELECT UserId from AspNetUserRoles where RoleId = 1)");
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds, "Reviewer");
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindDropDownList1(); //bindgridview will get the data source and bind it again
}
protected void DeleteRecord(object sender, GridViewDeleteEventArgs e)
{
string UserId = GridView1.DataKeys[e.RowIndex].Value.ToString();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString());
SqlCommand dCmd = new SqlCommand();
{
conn.Open();
dCmd.CommandText = "Reviewer_Delete";
dCmd.CommandType = CommandType.StoredProcedure;
dCmd.Parameters.Add("#UserId", SqlDbType.NVarChar).Value = UserId;
dCmd.Connection = conn;
dCmd.ExecuteNonQuery();
// Refresh the data
BindDropDownList1();
dCmd.Dispose();
conn.Close();
conn.Dispose();
}
}
}
}
Try to use the OnRowCommand event of the GridView to handle this.
In your Gridview markup:
ensure OnRowCommand="GridView1_RowCommand" is present.
In your code behind:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{ /* Set a breakpoint here and make sure:
A.) You are hitting this method
B.) Get value of e.CommandName */
if (e.CommandName == "EditRecord")
{
// Run your edit/update logic here if needed
}
if (e.CommandName == "DeleteRecord")
{
// Delete the record here
string UserId = GridView1.DataKeys[e.RowIndex].Value.ToString();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString());
SqlCommand dCmd = new SqlCommand();
{
conn.Open();
dCmd.CommandText = "Reviewer_Delete";
dCmd.CommandType = CommandType.StoredProcedure;
dCmd.Parameters.Add("#UserId", SqlDbType.NVarChar).Value = UserId;
dCmd.Connection = conn;
dCmd.ExecuteNonQuery();
// Refresh the data
BindDropDownList1();
dCmd.Dispose();
conn.Close();
conn.Dispose();
}
}
This ended up being a very simple thing. On the aspx page I had both the OnRowDeleting and CommandName elements set to the same value of "DeleteRecord".
Changing the CommandName value to "Delete" allowed the code to be evaluated and the stored procedure to be called successfully.
Related
I'm noobie to this :)
I'm getting data from SQL Server in the page_load event handler, and that works fine with SqlDataReader.
I also added a DataTable. I want to use the data when selecting a dropdownlist.
This is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string mainconn1 = ConfigurationManager.ConnectionStrings["SqlConnection1"].ConnectionString;
SqlConnection sqlconn1 = new SqlConnection(mainconn1);
string Sqlquery1 = "SELECT p.[Name], m.machineid,md.MachineNumber, md.HostName FROM [db].[dbo].[Machine] m INNER JOIN MachineDevice md ON md.MachineID = m.MachineID INNER JOIN property p ON m.PropertyID = p.PropertyID WHERE ([status] = '1') AND (md.DateTimeRetired IS NULL) ORDER BY md.MachineNumber";
SqlCommand sqlcomm1 = new SqlCommand(Sqlquery1, sqlconn1);
sqlconn1.Open();
SqlDataReader rd1 = sqlcomm1.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(rd1);
}
}
And this:
protected void Ort_SelectedIndexChanged1(object sender, EventArgs e)
{
if (Ort.SelectedValue == "Stockholm")
{
// while (rd1.read)
// {
// Machine.DataSource = rd1;
// Machine.DataTextField = "MachineNumber";
// Machine.DataValueField = "MachineNumber";
// Machine.DataBind();
// Machine.Items.Insert(0, new ListItem("-Select Machine-", "0"));
// }
}
}
Is it possible to get data when selectindexchanged, or do I need to ask SQL Server again?
Thanks
Sure, say we have a drop down (combo box) of some cities, and when you select the city, we fill out a gird of hotels.
Is it possible to get data when selectindexchanged, or do I need to ask SQL Server again?
you could in some cases "persist" the data, but the cost is just as high as in most cases hitting the database again.
so, yes, it is standard fair to re-pull that data.
example:
this markup:
<h3>Select Hotel city</h3>
<asp:DropDownList ID="DropDownList1" runat="server"
Width="150px" Height="30px"
DataTextField="City"
AutoPostBack="true"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<br />
<br />
<asp:GridView ID="GVHotels" runat="server" CssClass="table table-hover"
DataKeyNames="ID" AutoGenerateColumns="false" Width="40%" OnRowDataBound="GVHotels_RowDataBound" >
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="First Name" HeaderStyle-Width="100" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" HeaderStyle-Width="100" />
<asp:BoundField DataField="HotelName" HeaderText="Hotel Name" HeaderStyle-Width="120"/>
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="Description" HeaderText="Province" />
<asp:TemplateField>
<ItemTemplate>
<button runat="server" id="cmdEditBooking"
type="button" class="btn myshadow"
onserverclick="cmdEditBooking_ServerClick">
<span class="glyphicon glyphicon-home"></span>View
</button>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
So, we have a combo box (dropdown list) of city to select, and then we display hotels from that city.
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadCombo();
}
void LoadCombo()
{
string strSQL = "SELECT City FROM City ORDER BY City";
SqlCommand cmdSQL = new SqlCommand(strSQL);
DropDownList1.DataSource = MyRstP(cmdSQL);
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("Select City", ""));
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedIndex >0)
{
string strSQL =
#"SELECT * FROM tblHotelsA
WHERE City = #City
ORDER BY HotelName";
SqlCommand cmdSQL = new SqlCommand(strSQL);
cmdSQL.Parameters.Add("#City", SqlDbType.NVarChar).Value = DropDownList1.Text;
GVHotels.DataSource = MyRstP(cmdSQL);
GVHotels.DataBind();
}
}
And both of above use this handy helper routine:
DataTable MyRstP(SqlCommand cmdSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (cmdSQL)
{
cmdSQL.Connection = conn;
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
So, result:
So I want to make my dropdownlist to have always the same index selected, for example I have a gridview and I have a pager on it, if I change the page the index I had in my dropdownlist resets and I can give other example, I have a search textbox in my page and if I search something on it when I press enter the dropdownlist resets once again. How can I make my dropdownlist to have always the same selected index?
asp.net
<asp:GridView ID="MyGrid" runat="server"
DataKeyNames="No_" AutoGenerateColumns="false" Style="color: Black; border-collapse: collapse; margin-right: auto; display: table; text-align: center;" OnPageIndexChanging="MyGrid_PageIndexChanging" OnRowDataBound="MyGrid_RowDataBound" AllowPaging="True" OnPageIndexChanged="MyGrid_PageIndexChanged" PageSize="10" AllowCustomPaging="False">
<Columns>
<asp:BoundField DataField="No_" HeaderText="No_Encomenda" />
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" OnCheckedChanged="CheckBox1_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerSettings Mode="NumericFirstLast" PageButtonCount="4" FirstPageText="First" LastPageText="Last" />
<PagerStyle CssClass="gridview" HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:GridView>
cs
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["constring"].ConnectionString);
List<string> MySelected;
protected void Page_Load(object sender, EventArgs e)
{
ButtonBack.Visible = false;
//GridView1.Visible = false;
con.Open();
SqlCommand cmd = new SqlCommand("Select bl from booking", con);
SqlDataReader sdr = cmd.ExecuteReader();
DropDownList1.Items.Clear();
DropDownList1.Items.Add("-");
if(IsPostBack == false)
{
while (sdr.Read())
{
DropDownList1.Items.Add(sdr.GetValue(0).ToString());
}
}
if (IsPostBack == false)
{
MySelected = new List<string>();
LoadGrid();
ViewState["MySelected"] = MySelected;
}
else
{
MySelected = (List<string>)ViewState["MySelected"];
}
string user = Convert.ToString(Session["user"]);
username.Text = user;
if (Session["user"] == null || Session["login"] == null)
{
Response.Redirect("Login.aspx", false);
}
if (!Page.IsPostBack)
{
refreshdata();
refreshdata();
}
con.Close();
}
public void LoadGrid()
{
SqlCommand cmd = new SqlCommand("select DISTINCT No_ from [EncomendaTEMP]", con);
{
DataTable rst = new DataTable();
rst.Load(cmd.ExecuteReader());
MyGrid.DataSource = rst;
MyGrid.DataBind();
}
}
public void refreshdata()
{
SqlCommand cmd = new SqlCommand("select DISTINCT No_ from [EncomendaTEMP]", con);
{
DataTable rst = new DataTable();
rst.Load(cmd.ExecuteReader());
MyGrid.DataSource = rst;
MyGrid.DataBind();
}
}
In Page_Load code, I see that you are loading data in dropdownlist. When the page is submitted, Page_Load will execute and it will reload the data in the dropdown list. That's why selection goes off.
You should load the data in the dropdown list only during first load of the page. As you are doing with LoadGrid(). During post back the data of the dropdown and selection will be maintained if you don't reload them.
So I suggest following code change for loading data in dropdown list.
if(!IsPostBack)
{
SqlCommand cmd = new SqlCommand("Select bl from booking", con);
SqlDataReader sdr = cmd.ExecuteReader();
DropDownList1.Items.Clear();
DropDownList1.Items.Add("-");
while (sdr.Read())
{
DropDownList1.Items.Add(sdr.GetValue(0).ToString());
}
MySelected = new List<string>();
LoadGrid();
ViewState["MySelected"] = MySelected;
}
else
{
MySelected = (List<string>)ViewState["MySelected"];
}
I hope this will help you solve your problem.
I'm working in Visual Studio 2015.
When the Gridview loads, I can click on "Edit".
When I click Cancel I'm just getting back to the Gridview.
So that good, but if I click "Update" he is doing the same thing as what is happening at "Cancel". No errors.
Here is the method for the OnRowUpdating :
protected void UpdateHandleiding(object sender, GridViewUpdateEventArgs e)
{
SqlConnection Sqlconnection1 = new SqlConnection();
Sqlconnection1.ConnectionString = (System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
//string ID = ((Label)GridView1.Rows[e.RowIndex].FindControl("lblID")).Text;
//string Naam = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtNaam")).Text;
//string URL = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtURL")).Text;
GridViewRow row = GridView1.Rows[e.RowIndex];
int ID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
string Naam = (row.Cells[1].Controls[0] as TextBox).Text;
string URL = (row.Cells[2].Controls[0] as TextBox).Text;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand("UPDATE Handleidingen SET Naam=#Naam, URL=#URL WHERE ID=#ID"))
{
cmd.Parameters.AddWithValue("#ID", ID);
cmd.Parameters.AddWithValue("#Naam", Naam);
cmd.Parameters.AddWithValue("#URL", URL);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
GridView1.EditIndex = -1;
GridView1.DataBind();
}
Here is my OnRowEditing & OnRowCancelingEdit which do work :
protected void EditHandleiding(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
ShowHandleidingen();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
ShowHandleidingen();
}
Here is my Gridview :
<asp:GridView ID="GridView1" runat="server" CssClass="grid-center" AutoGenerateColumns="False"
DataKeyNames="ID" EnableModelValidation="True" OnRowDeleting="GridView1_RowDeleting"
OnRowEditing="EditHandleiding" OnRowUpdating="UpdateHandleiding" OnRowCancelingEdit="CancelEdit">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Naam" HeaderText="Naam"/>
<asp:BoundField DataField="URL" HeaderText="URL"/>
<asp:CommandField ShowEditButton="True" />
<asp:CommandField ShowDeleteButton="true" />
</Columns>
</asp:GridView>
this is simple situation caused by the post back events in asp.net, in the Update Method the page is reloaded from the begining, even if you give new values to the data that you want too submit in the database, asp.net will take the one in the page_load method, when you fill the database in the first place at the page_load method add this condition :
private void Page_Load()
{
if (!IsPostBack)
{
// Fill up the gridView with the data that you want
}
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
}
replace object sender, GridViewUpdateEventArgs e
to
object sender, GridViewRowEventArgs e
Simply change gridview in aspx page
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound">
and then put
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{}
All I want to do is when A user clicks on "See more" button on gridview, He will get all the columns of the row button clicked on detailView1.. But I dont know where Im going wrong. Im working on C# asp.net
Can anyone help? Thanks in advance.
protected void Page_Load(object sender, EventArgs e)
{
var conString = ConfigurationManager.ConnectionStrings["CONSTRING"].ConnectionString;
SqlConnection con = new SqlConnection(conString);
DetailsView1.Visible = false;
SqlCommand cmd1 = new SqlCommand("SELECT cars.carid, cars.make, cars.model, cars.condition, cars.amount, img.img FROM cars INNER JOIN img ON cars.carid = img.carid ", con);
SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
DataTable dt = new DataTable();
sda1.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void Button2_Clicked(object sender, EventArgs e)
{
var conString = ConfigurationManager.ConnectionStrings["CONSTRING"].ConnectionString;
SqlConnection con = new SqlConnection(conString);
foreach (GridViewRow row in this.GridView1.Rows)
{
Label lblshow = (Label)GridView1.Rows[row.RowIndex].FindControl("carid");
SqlCommand cmd1 = new SqlCommand("Select * from cars where carid='" + lblshow.Text + "'", con);
SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
DataTable dt = new DataTable();
sda1.Fill(dt);
DetailsView1.DataSource = dt;
DetailsView1.DataBind();
}
}
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="True" Width="1000px" AllowPaging="True" PageSize="8" CssClass="Grid" AlternatingRowStyle-CssClass="alt" PagerStyle-CssClass="pgr">
<AlternatingRowStyle CssClass="alt"></AlternatingRowStyle><PagerStyle CssClass="pgr"></PagerStyle>
<Columns>
<asp:TemplateField>
<HeaderTemplate>Select</HeaderTemplate>
<ItemTemplate>
<asp:Button runat="server" Text="See more" OnClick="Button2_Clicked" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>Image</HeaderTemplate>
<ItemTemplate>
<img src='data:image/jpg;base64,<%# Eval("img") != System.DBNull.Value ? Convert.ToBase64String((byte[])Eval("img")) : string.Empty %>' alt="image" height="100" width="150"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
IsPostback on the page load event. Hope your problem get resolved.
I got a problem with my GridView. When I try to edit my GridView, I only get the old values in return.
Here's the RowUpdating event:
protected void grid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
TextBox nVorname = (TextBox)row.FindControl("newVorname");
TextBox nNachname = (TextBox)row.FindControl("newNachname");
TextBox nTelnr = (TextBox)row.FindControl("newTelnr");
TextBox nEmail = (TextBox)row.FindControl("newEmail");
HiddenField tid = (HiddenField)row.FindControl("id");
grid.EditIndex = -1;
SqlConnection sqlConn = new SqlConnection("server=localhost;Integrated Security=true;database=Telefonbuch;");
sqlConn.Open();
SqlCommand cmd = new SqlCommand("update dasOertliche set vorname= #vorname, nachname=#nachname, telefonnr =#telnr, email =#email where id = #id", sqlConn);
cmd.Parameters.Add("#vorname", SqlDbType.VarChar);
cmd.Parameters["#vorname"].Value = nVorname;
cmd.Parameters.Add("#nachname", SqlDbType.VarChar);
cmd.Parameters["#nachname"].Value = nNachname.Text;
cmd.Parameters.Add("#email", SqlDbType.VarChar);
cmd.Parameters["#email"].Value = nEmail.Text;
cmd.Parameters.Add("#telnr", SqlDbType.VarChar);
cmd.Parameters["#telnr"].Value = nTelnr.Text;
cmd.Parameters.Add("#id", SqlDbType.Int);
cmd.Parameters["#id"].Value = tid.Value;
cmd.ExecuteNonQuery();
sqlConn.Close();
bind();
}
The TemplateField from the .aspx:
<Columns>
<asp:TemplateField HeaderText = "Vorname">
<ItemTemplate> <%#Eval ("vorname") %></ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="newVorname" runat="server" Text='<%#Eval ("vorname") %>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</columns>
And my GridView code:
<asp:GridView runat="server" ID="grid" BorderWidth="0px" CellPadding="10"
CellSpacing="10" HorizontalAlign="Center" AutoGenerateDeleteButton="True"
AutoGenerateEditButton="True" onrowcancelingedit="grid_RowCancelingEdit"
onrowediting="grid_RowEditing" onrowupdating="grid_RowUpdating"
AutoGenerateColumns="False">
Like I said, it always returns the old values. Any suggestions?
My Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
bind();
if (!Page.IsPostBack)
{
bind();
}
}
My bind():
public void bind()
{
SqlConnection sqlConn = new SqlConnection("server=localhost;Integrated Security=true;database=Telefonbuch;");
sqlConn.Open();
SqlDataAdapter sqlComm = new SqlDataAdapter("SELECT id, vorname AS 'Vorname', nachname AS 'Nachname', telefonnr, email AS 'E-Mail' FROM dasOertliche ORDER BY nachname ASC", sqlConn);
DataSet ds = new DataSet();
sqlComm.Fill(ds, "dasOertliche");
grid.DataSource = ds.Tables[0];
grid.DataBind();
sqlConn.Close();
}
protected void Page_Load(object sender, EventArgs e)
{
bind();
if (!Page.IsPostBack)
{
bind();
}
}
is wrong.
It should be:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
bind();
}
}
On Pageload put your bind grid code in following condition
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
bind();
}
}
You need to call GridView1.DataBind() in the end.