Hi I am wondering how I can change the header text of my column in my Gridview when I am pulling from a Database to build my Gridview.
Here is how I am building the GridView.
SqlConnection Conn = new SqlConnection("REMOVED");
SqlDataReader rdr = null;
string commandString = "SELECT OrderNumber, CreatedDate, CreatedBy, CustomerID, Store_Number, Package FROM dbo.Orderheader";
try
{
Conn.Open();
SqlCommand Cmd = new SqlCommand(commandString, Conn);
rdr = Cmd.ExecuteReader();
GridView1.DataSource = rdr;
GridView1.DataBind();
}
catch (Exception ex)
{
// Log error
}
finally
{
if (rdr != null)
{
rdr.Close();
}
if (Conn != null)
{
Conn.Close();
}
}
}
Get the header row object in databound event and change the desired name,
void GridView1_DataBound(Object sender, EventArgs e)
{
// Get the header row.
GridViewRow headerRow = GridView1.HeaderRow;
headerRow.Cells[0].Text = "Order";
headerRow.Cells[1].Text = "Date";
}
OR
Set AutoGenerateColumns to False and use Column bound fields,
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<columns>
<asp:BoundField HeaderText="Order" DataField="OrderNumber" />
<asp:BoundField HeaderText="Date" DataField="CreatedDate" />
</columns>
</asp:GridView>
Related
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.
So basically i want to create a booking and a booking can have multiple orders but i dont know how to store the orders that have been selected in the other pages etc. but I already know i have to do a cycle to run the gridview bue i dont know how to do that with a pager and with a search textbox.
this is how it looks:
Current CS
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Gestão_de_embarques
{
public partial class CriarEcomenda : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["constring"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
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();
}
con.Close();
}
public void refreshdata()
{
SqlCommand cmd = new SqlCommand("select DISTINCT No_ from [Encomenda]", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void btnsearch_Click(object sender, EventArgs e)
{
con.Open();
if (txtSearch.Value == "")
{
refreshdata();
}
else
{
try
{
SqlCommand cmd = new SqlCommand("select DISTINCT No_ from [encomenda] where No_= #No_", con);
cmd.Parameters.Add("#No_", SqlDbType.NVarChar).Value = txtSearch.Value;
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.Read())
{
sdr.Close();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
else
{
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sdr.Close();
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
ButtonCreate.Visible = false;
}
}
catch(Exception ex)
{
}
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
refreshdata();
}
}
}
Well, if you were not data paging, then the un-bound check box would persist and survive even post backs.
But, since you have data paging? Then you persist the selected PK id from the database. (you don't have to display the pk row, but just set DataKeys = "ID" or what ever your PK row is from the database.
As noted, with searching and paging, you have to re-bind the grid, so you can't use the grid to persist the selected check boxes. Say we have a list of hotels to select.
Our markup would be this:
<div style="width:40%">
<asp:GridView ID="MyGrid" runat="server" CssClass="table table-hover"
DataKeyNames="ID" AutoGenerateColumns="false" OnRowDataBound="MyGrid_RowDataBound" >
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" />
<asp:BoundField DataField="HotelName" HeaderText="Hotel Name" />
<asp:BoundField DataField="HotelName" HeaderText="Hotel Name" />
<asp:BoundField DataField="Province" HeaderText="Province" />
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" OnCheckedChanged="CheckBox1_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="Button1" runat="server" Text="Show Selected rows" OnClick="Button1_Click" />
<br />
<br />
</div>
And code to load up this grid would be:
List<int> MySelected = new List<int>();
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
LoadGrid();
ViewState["MySelected"] = MySelected;
}
else
{
MySelected = (List<int>)ViewState["MySelected"];
}
}
public void LoadGrid()
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * from tblHotels ORDER BY HotelName",
new SqlConnection(Properties.Settings.Default.TEST3)))
{
cmdSQL.Connection.Open();
DataTable rst = new DataTable();
rst.Load(cmdSQL.ExecuteReader());
MyGrid.DataSource = rst;
MyGrid.DataBind();
}
}
protected void MyGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int PkRow = (int)((DataRowView)e.Row.DataItem)["ID"];
CheckBox ckbox = (CheckBox)e.Row.FindControl("CheckBox1");
if (MySelected.Contains(PkRow)) {
ckbox.Checked = true;
}
}
}
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
CheckBox ckBox = (CheckBox)sender;
GridViewRow gvRow = (GridViewRow)ckBox.Parent.Parent;
int RowPK = (int)(MyGrid.DataKeys[gvRow.RowIndex]["ID"]);
if (ckBox.Checked)
MySelected.Add(RowPK);
else
MySelected.Remove(RowPK);
}
Now how I just created a simple list. When you check a box, you simply add the PK row from the GridRow "PK" to the list.
The code to get/work the "list" from the database thus will look like this:
protected void Button1_Click(object sender, EventArgs e)
{
string MyPkList = string.Join(",", MySelected);
string strSQL = "SELECT * from tblHotels where ID IN(" + MyPkList + ")";
using (SqlCommand cmdSQL = new SqlCommand(strSQL, new SqlConnection(Properties.Settings.Default.TEST3)))
{
cmdSQL.Connection.Open();
DataTable rstPickList = new DataTable();
rstPickList.Load(cmdSQL.ExecuteReader());
foreach (DataRow OneRow in rstPickList.Rows)
{
Response.Write("<h2> PK = " + OneRow["Id"].ToString() + " Hotel Name = " + OneRow["HotelName"] + "</h2>");
}
}
}
So, if I check say 3 rows, and hit that button, you get this:
this does mean that you have to set the check box to auto post back. And that thus means for a check box click, you do post-back. However, you could drop the whole grid in a update panel if you need to only post back that grid selecting part and not the whole page.
Once you have that list of PK values from the database, then as the button shows, we have to process against the database table, and we can't use the grid due to paging. As noted, if the gridview could fit on one page, then you would not need the persisting code, and you could just loop the grid view to get the checked rows - you would not need ANY code to persist the values.
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.
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string VisitorManagementConnectionString = ConfigurationManager.ConnectionStrings["VisitorManagementConnectionString"].ConnectionString;
string strQuery = "select Id, ItemName, FoundAt, TimeIn, ImageName from LostFound order by ID";
SqlCommand cmd = new SqlCommand(strQuery);
SqlConnection con = new SqlConnection(VisitorManagementConnectionString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
ViewState["dt"] = dt;
BindGrid();
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
dt.Dispose();
}
}
protected void BindGrid()
{
GridView1.DataSource = ViewState["dt"] as DataTable;
GridView1.DataBind();
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void BtnLose_Click(object sender, EventArgs e)
{
Response.Redirect("SecurityLost.aspx");
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string ID = e.Row.Cells[0].Text;
foreach (Button button in e.Row.Cells[5].Controls.OfType<Button>())
{
if (button.CommandName == "Delete")
{
button.Attributes["onclick"] = "if(!confirm('Do you want to delete " + ID + "?')){ return false; };";
}
}
}
}
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
int ID = Convert.ToInt32(e.RowIndex);
DataTable dt = ViewState["dt"] as DataTable;
dt.Rows[ID].Delete();
string VisitorManagementConnectionString = ConfigurationManager.ConnectionStrings["VisitorManagementConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(VisitorManagementConnectionString))
{
using (SqlCommand cmd = new SqlCommand("DELETE FROM LostFound WHERE ID = #ID"))
{
cmd.Parameters.AddWithValue("#ID", ID);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
BindGrid();
}
when i press delete button the row can be delete but when i reload the
page the row i deleted still appeal back and my database also never be
deleted.
Can someone guide me where am I going wrong?
<asp:GridView ID="GridView1" runat="server" OnRowDataBound = "OnRowDataBound" AutoGenerateColumns = "false" OnRowDeleting="OnRowDeleting" Font-Names = "Arial" Caption = "Lose & Found" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField = "ID" HeaderText = "ID" />
<asp:BoundField DataField = "ItemName" HeaderText = "Item Name" />
<asp:BoundField DataField = "FoundAt" HeaderText = "Place" />
<asp:BoundField DataField = "TimeIn" HeaderText = "Time Found" />
<asp:ImageField DataImageUrlField = "ID" DataImageUrlFormatString = "Image.aspx?ImageID={0}" ControlStyle-Width = "100" ControlStyle-Height = "100" HeaderText = "Preview Image"/>
<asp:CommandField ShowDeleteButton="True" ButtonType="Button" />
</Columns>
</asp:GridView>
This my HTML file.
So from the comments we've established that the problem is that your ID is always 0.To make sure the ID comes through correctly you need to make two changes:
1.Change the Page_Load() event like this:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
//Cut and paste the code to bind to the GridView here
}
}
2.Add this code to the RowDeleting event:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int id = Int32.Parse(GridView1.Rows[e.RowIndex].Cells[0].Text);
}
I have an old web forms project on support. And I can't understand what I'm doing wrong with paging. I have this code:
<asp:GridView ID="gvProducts" runat="server"
AllowSorting="True" AllowPaging ="true" PageSize="20"
AutoGenerateColumns="False" DataKeyNames="products_id" CssClass="gridview" OnRowCommand="gvProducts_RowCommand"
OnSelectedIndexChanging="gvProducts_SelectedIndexChanging"
OnRowDataBound="gvProducts_RowDataBound"
OnPageIndexChanging="gvProducts_PageIndexChanging"
DataSourceID="dsSearchResult" >
<PagerTemplate>
<asp:GridViewPager ID="GridViewPager1" runat="server" />
</PagerTemplate>
This is data sourse:
<asp:ObjectDataSource ID="dsSearchResult" runat="server" SelectMethod="GetFindedProducts"
EnableViewState ="true" ViewStateMode="Enabled"
EnablePaging="True" TypeName="Paging.ResultSearch"
SortParameterName="sortExpression">
And this is page index changing method:
protected void gvProducts_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvProducts.PageIndex = e.NewPageIndex;
gvProducts.DataBind();
}
When I click on paging buttons nothing happends (just numbers of pages changes). I've tryed to find solution, but all resolves doesn't work.
And this is my SelectMethod:
public List<BOM.SearchProducts_pagedResult_ext> GetFindedProducts(int maximumRows, int startPageIndex, int startRowIndex, string sortExpression, string model, string param)
{
SphinxClient client = new SphinxClient();
string idProducts = client.GetIdProducts(model);
SqlConnection connection = new SqlConnection(Globals.ConnectionString);
string cmdText = "SearchProducts";
SqlCommand command = new SqlCommand(cmdText, connection);
command.CommandType = CommandType.StoredProcedure; // it's a default value
command.CommandTimeout = 100;
command.Connection = connection;
command.Parameters.Add("#id_array", SqlDbType.NVarChar).Value = idProducts;
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(command);
try
{
connection.Open();
adapter.Fill(ds);
}
catch (Exception ex)
{
if (connection.State == ConnectionState.Open)
connection.Close();
throw new Exception("Can't get the list of products/GetProductsDataSet!", ex);
}
finally
{
connection.Close();
}
return TopagedResult_ext(ds);
}
public List<BOM.SearchProducts_pagedResult_ext> TopagedResult_ext(DataSet q)
{
DataRowCollection dr = q.Tables[0].Rows;
List<BOM.SearchProducts_pagedResult_ext> searchResultArr = new List<BOM.SearchProducts_pagedResult_ext>();
DataRow r;
//BOM.SearchProducts_pagedResult searchResult;
BOM.SearchProducts_pagedResult_ext searchResult_ext;
for (int i=0; i < dr.Count; i++)
{
r = dr[i];
searchResult_ext = fillData(r);
searchResultArr.Add(searchResult_ext);
}
return searchResultArr;
}
May anyone help me?