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?
Related
I want to get what I write in the textbox but always get the "" string. I can't find the value when I type something else into the textboxT_T.
Here is the Gridview code:
<div style="margin:0 auto;width:900px;">
<asp:Label ID="USER_header" runat="server"
Text="一.先新增用戶" CssClass="=text-center"></asp:Label>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" ShowFooter = "true" Width="900" OnDataBound = "OnDataBound" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField HeaderText="工號" SortExpression="BS_ID">
<ItemTemplate>
<asp:Label ID="lblBSID" runat="server"
Text='<%# Eval("BS_ID") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="BS_ID_tb" runat="server"/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="中文姓名" SortExpression="BS_NAME_CHT">
<ItemTemplate>
<asp:Label ID="lblBS_NAME_CHT" runat="server"
Text='<%# Eval("BS_NAME_CHT") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="BS_NAME_CHT_tb" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="英文姓名" SortExpression="BS_NAME_ENG">
<ItemTemplate>
<asp:Label ID="lblBS_NAME_ENG" runat="server"
Text='<%# Eval("BS_NAME_ENG") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="BS_NAME_ENG_tb" runat="server" ></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="部門" SortExpression="BS_DEPT">
<ItemTemplate>
<asp:Label ID="lblBS_DEPT" runat="server"
Text='<%# Eval("BS_DEPT") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="DropDownList1" Width="200" runat="server">
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<FooterTemplate>
<asp:LinkButton ID="btnInsert" runat="server"
onclick="lbInsert_Click" Text="新增" CommandName="Insert"></asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>`
Here is the complete code:
private DataSet _dataSet;
private DataSet _dataSetHKTEL;
private DataSet _datasetHKMOBILE;
private string _value;
protected void Page_Load(object sender, EventArgs e)
{
ShowData();
GridView1.FooterRow.Visible = false;
lblinsertuser.Visible = false;
lbCancelSave.Visible = false;
//if (Session["key_pass"] == null)
//{
// Response.Write("<script>alert('YOUR ACCESS DENY! 你沒有權限進入此頁面');location.href='Default.aspx';</script>");
//}
}
private void Viewtable()
{
using (SqlConnection conn = new SqlConnection(this._connectionString))
{
string query = "SELECT TOP 2 BS_ID,BS_NAME_CHT,BS_NAME_ENG,BS_DEPT FROM BS_USER ORDER BY 1 DESC ";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da1 = new SqlDataAdapter(cmd);
DataTable finaldata = this.GenerateDataTable();
conn.Open();
da1.Fill(finaldata);
this._dataSet = new DataSet();
this._dataSet.Tables.Add(finaldata);
conn.Close();
da1.Dispose();
}
}
private void ViewItnlHKTel()
{
using (SqlConnection conn = new SqlConnection(this._connectionString))
{
string query = "SELECT TOP 2 DA_TEL_NO,DA_USER FROM DA_ITNL_HK_TEL ORDER BY 1 DESC ";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da1 = new SqlDataAdapter(cmd);
DataTable finaldata = this.GenerateTable();
conn.Open();
da1.Fill(finaldata);
this._dataSetHKTEL = new DataSet();
this._dataSetHKTEL.Tables.Add(finaldata);
conn.Close();
da1.Dispose();
}
}
private void ViewITNLHKMOBILE()
{
using (SqlConnection conn = new SqlConnection(this._connectionString))
{
string query = "SELECT TOP 2 DA_PHONE_NO,DA_USER FROM DA_HK_MOBILE ORDER BY 1 DESC ";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da1 = new SqlDataAdapter(cmd);
DataTable finaldata = this.GenerateMOBILE_HK();
conn.Open();
da1.Fill(finaldata);
this._datasetHKMOBILE = new DataSet();
this._datasetHKMOBILE.Tables.Add(finaldata);
conn.Close();
da1.Dispose();
}
}
private DataTable GenerateDataTable()
{
DataTable table = new DataTable();
table.Columns.Add("BS_ID", typeof(string));
table.Columns.Add("BS_NAME_CHT", typeof(string));
table.Columns.Add("BS_NAME_ENG", typeof(string));
table.Columns.Add("BS_DEPT", typeof(string));
return table;
}
private DataTable GenerateTable()
{
DataTable table = new DataTable();
table.Columns.Add("DA_USER", typeof(string));
table.Columns.Add("DA_ITNL_HK_TEL", typeof(string));
return table;
}
private DataTable GenerateMOBILE_HK()
{
DataTable table = new DataTable();
table.Columns.Add("DA_USER", typeof(string));
table.Columns.Add("DA_PHONE_NO", typeof(string));
return table;
}
private void ShowData()
{
Viewtable();
GridView1.DataSource = this._dataSet;
GridView1.DataBind();
ViewItnlHKTel();
ADD_HK_TEL.DataSource = this._dataSetHKTEL;
ADD_HK_TEL.DataBind();
ViewITNLHKMOBILE();
ADD_HK_MOBILE.DataSource = this._datasetHKMOBILE;
ADD_HK_MOBILE.DataBind();
}
protected void lbladd_Click(object sender, EventArgs e)
{
//TextBox id = GridView1.FooterRow.FindControl("BS_ID_tb") as TextBox;
////string strBS_ID = (GridView1.FooterRow.FindControl("BS_ID_tb") as TextBox).Text;
//DropDownList DEPT_ddl = GridView1.FooterRow.FindControl("DropDownList1") as DropDownList;
////string strBS_ID = BS_ID_tb.Text;
////string strBS_NAME_CHT = BS_NAME_CHT_tb.Text;
////string strBS_NAME_ENG = BS_NAME_ENG.Text;
//string strBS_DEPT = DEPT_ddl.SelectedItem.Value;
////using (SqlConnection conn = new SqlConnection(this._connectionString))
////{
//// string query = "INSERT INTO BS_USER(BS_ID , BS_NAME_CHT , BS_NAME_ENG , BS_DEPT) VALUES (#BS_ID , #BS_NAME_CHT , #BS_NAME_ENG , #BS_DEPT)";
//// SqlCommand cmd = new SqlCommand(query, conn);
//// cmd.Parameters.Clear();
//// cmd.Parameters.AddWithValue("#BS_ID", strBS_ID);
//// cmd.Parameters.AddWithValue("#BS_NAME_CHT", strBS_NAME_CHT);
//// cmd.Parameters.AddWithValue("#BS_NAME_ENG", strBS_NAME_ENG);
//// cmd.Parameters.AddWithValue("#BS_DEPT", strBS_DEPT);
//// conn.Open();
//// cmd.ExecuteReader();
//// conn.Close();
//// //Response.Redirect("");
////}
}
protected void lbInsert_Click(object sender, EventArgs e)
{
GridView1.FooterRow.Visible = true;
lblinsertuser.Visible = true;
lbCancelSave.Visible = true;
lbInsert.Visible = false;
}
protected void lbCancelSave_Click(object sender, EventArgs e)
{
GridView1.FooterRow.Visible = false;
lbInsert.Visible = true;
}
DataTable Selectindex()
{
DataTable dt = new DataTable();
try
{
using (SqlConnection conn = new SqlConnection(this._connectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT '請選擇部門' AS BS_NAME , '000' AS BS_ID UNION SELECT BS_NAME , BS_ID FROM BS_DEPT ORDER BY BS_ID ASC", conn))
{
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
}
}
}
catch (SqlException exc)
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + exc.Message + "');", true);
}
catch (Exception exc)
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + exc.Message + "');", true);
}
finally
{
}
return dt;
}
protected void OnDataBound(object sender, EventArgs e)
{
DropDownList DEPT_ddl = GridView1.FooterRow.FindControl("DropDownList1") as DropDownList;
DEPT_ddl.DataSource = Selectindex();
DEPT_ddl.DataTextField = "BS_NAME";
DEPT_ddl.DataValueField = "BS_ID";
DEPT_ddl.DataBind();
}
protected void lbSave_Click(object sender, EventArgs e)
{
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Insert",StringComparison.OrdinalIgnoreCase))
{
GridView GridView1= (GridView)sender;
TextBox BS_ID_tb = (TextBox)GridView1.FooterRow.FindControl("BS_ID_tb");
string str_BS_ID = BS_ID_tb.Text;
TextBox BS_NAME_CHT_tb = (TextBox)GridView1.FooterRow.FindControl("BS_NAME_CHT_tb");
string str_BS_NAME_CHT = BS_NAME_CHT_tb.Text;
TextBox BS_NAME_ENG_tb = (TextBox)GridView1.FooterRow.FindControl("BS_NAME_ENG_tb");
string str_BS_NAME_ENG_tb = BS_NAME_ENG_tb.Text;
DropDownList DEPT_ddl = (DropDownList)GridView1.FooterRow.FindControl("DropDownList1");
string str_DEPT_value = DEPT_ddl.SelectedItem.Value;
InsertData(str_BS_ID, str_BS_NAME_CHT, str_BS_NAME_ENG_tb, str_DEPT_value);
GridView1.ShowFooter = false;
ShowData();
GridView1.FooterRow.Visible = false;
lblinsertuser.Visible = false;
lbCancelSave.Visible = false;
}
}
private void InsertData(string BS_ID, string BS_NAME_CHT, string BS_NAME_ENG, string BS_DEPT)
{
using (SqlConnection conn = new SqlConnection(this._connectionString))
{
conn.Open();
string sql = String.Format("Insert into BS_USER VALUES('{0}','{1}','{2}','{3}')", BS_ID, BS_NAME_CHT, BS_NAME_ENG, BS_DEPT);
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
}
}
View state's purpose is simple:
it's there to persist state across postbacks.
That's why you are getting the initial values like empty strings in the gridview. Setting the property EnableViewState="false" force to get the data by rebinding the control, not from the viewstate. To understand view state more, see here.
I've encountered an error which is absolutely driving me insane. Forgive me, I'm a novice, so I may be missing something out which is stupid or silly so sorry in advance.
I keep getting the error
"Procedure or function 'prcPersonalSelectedByPatientIdAppointmentSelect' expects parameter '#PatientNumber', which was not supplied."
This is baffling to me as '#PatientNumber' is in the stored procedure but my knowledge of SQL isn't the greatest.
ASPX Code
<asp:UpdatePanel ID="pnlUpdate" runat="server">
<ContentTemplate>
<asp:Panel ID="pnlResults" runat="server" ScrollBars="Auto" >
<asp:GridView ID="gvAppointmentSearch" runat="server" Font-Names = "Arial"
Font-Size = "11pt" ForeColor = "#000000"
onselectedindexchanged="gvAppointmentSearch_SelectedIndexChanged"
AutoGenerateColumns = "false" DataKeyNames="PatientNumber" AllowPaging = "true"
OnPageIndexChanging = "OnPaging" PageSize = "10" Width = "100%"
HeaderStyle-BackColor = "#465c71" HeaderStyle-ForeColor = "#ffffff"
style="margin-bottom: 26px">
<Columns>
<%--Creates a select button that appear at the start of the grid view--%>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton Text="Select" ID="lnkSelect" runat="server" CommandName="Select" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Appointment Number" ItemStyle-Wrap="False">
<ItemTemplate>
<%--This will be the first field to appear beside the select button--%>
<asp:Label ID="lblAppointmentNumber" Text='<%# Eval("AppointmentNumber") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<%--Bound fields will place them in a specific order--%>
<asp:BoundField DataField = "AppointmentDate" HeaderText = "Appointment Date" DataFormatString="{0:d}" />
<asp:BoundField DataField = "AppointmentTime" HeaderText = "Appointment Time" DataFormatString="{0:d}" />
<asp:BoundField DataField = "Consultant" HeaderText="Referred By" ItemStyle-Wrap="False" />
<asp:BoundField DataField = "ByAttendance" HeaderText="Attendance"/>
</Columns>
</asp:GridView>
</asp:Panel>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="gvAppointmentSearch" />
</Triggers>
</asp:UpdatePanel>
C# Code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Populate dropdown if no record has been selected
String strConString = ConfigurationManager.ConnectionStrings["OepdSQLConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(strConString);
conn.ConnectionString = strConString;
SqlCommand cmdInit = new SqlCommand();
cmdInit.CommandText = "Select * from DropdownCounty";
cmdInit.Connection = conn;
conn.Open();
DataTable dtInit = new DataTable();
dtInit.Load(cmdInit.ExecuteReader());
conn.Close();
dpdCounty.DataSource = dtInit;
dpdCounty.DataTextField = "County";
dpdCounty.DataValueField = "CountyID";
dpdCounty.DataBind();
DataSet ds = new DataSet();
ds = (DataSet)Session["DS"];
this.DataBindSearch();
try
{
//Fields that are required to be filled in if the information is avaliable
patientNumber.Text = ds.Tables[0].Rows[0]["PatientNumber"].ToString();
txtHCNumber.Text = ds.Tables[0].Rows[0]["HC_Number"].ToString();
//if (ds.Tables[0].Rows[0]["ConsentToDatabase"].ToString() != null)
//chkDBConsent.Checked = (bool)ds.Tables[0].Rows[0]["ConsentToDatabase"];
if (ds.Tables[0].Rows[0]["ConsentGivenDate"].ToString() != "dd/mm/yyyy")
{
if (ds.Tables[0].Rows[0]["ConsentGivenDate"].ToString() != null && ds.Tables[0].Rows[0]["ConsentGivenDate"].ToString() != "")
{
ConsentGivenDate.Text = Convert.ToDateTime(ds.Tables[0].Rows[0]["ConsentGivenDate"].ToString()).ToShortDateString();
}
}
IDnumberLegacy.Text = ds.Tables[0].Rows[0]["ID_Number_LegacyID"].ToString();
if (ds.Tables[0].Rows[0]["Sex"] != DBNull.Value)
{
//Datasource is added only when values are being added to allow for alterations to be made
//Allows for records with older dropdown values no longer selectable to be visible
String strConnString = ConfigurationManager.ConnectionStrings["OepdSQLConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
con.ConnectionString = strConnString;
SqlCommand cmd = new SqlCommand();
SqlCommand cmdPop = new SqlCommand();
cmd.CommandText = "Select Sex from DropdownSex";
cmd.Connection = con;
con.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
con.Close();
//String builder to gather records that are currently active
StringBuilder currentid = new StringBuilder();
for (int i = dt.Rows.Count - 1; i >= 0; i--)
{
DataRow dr = dt.Rows[i];
currentid.AppendLine(string.Join(",", dr.ItemArray));
}
//convert stringbuilder to string
var output = currentid.ToString();
// Creates new StringReader instance from System.IO
using (StringReader reader = new StringReader(output))
{
// Loop over the lines in the string.
int count = 0;
string line;
while ((line = reader.ReadLine()) != null)
{
count++;
if (line == (ds.Tables[0].Rows[0]["Sex"].ToString()))
cmdPop.CommandText = " Select * From DropdownSex";
}
}
if (cmdPop.CommandText == "")
cmdPop.CommandText = " Select * From DropdownSex";
cmdPop.Connection = con;
con.Open();
DataTable dtValues = new DataTable();
dtValues.Load(cmdPop.ExecuteReader());
con.Close();
dpdSex.DataSource = dtValues;
dpdSex.DataTextField = "Sex";
dpdSex.DataValueField = "SexID";
dpdSex.DataBind();
dpdSex.SelectedValue = ds.Tables[0].Rows[0]["SexID"].ToString();
}
txtPatientFirstName.Text = ds.Tables[0].Rows[0]["Forename"].ToString();
txtPatientSurname.Text = ds.Tables[0].Rows[0]["Surname"].ToString();
PatientMaiden.Text = ds.Tables[0].Rows[0]["MaidenName"].ToString();
if (ds.Tables[0].Rows[0]["DateOfBirth"].ToString() != "dd/mm/yyyy")
{
if (ds.Tables[0].Rows[0]["DateOfBirth"].ToString() != null && ds.Tables[0].Rows[0]["DateOfBirth"].ToString() != "")
{
txtDateOfBirth.Text = Convert.ToDateTime(ds.Tables[0].Rows[0]["DateOfBirth"].ToString()).ToShortDateString();
}
}
AddressLine1.Text = ds.Tables[0].Rows[0]["AddressLine1"].ToString();
AddressLine2.Text = ds.Tables[0].Rows[0]["AddressLine2"].ToString();
AddressLine3.Text = ds.Tables[0].Rows[0]["AddressLine3_TownCity"].ToString();
AddressLine4.Text = ds.Tables[0].Rows[0]["AddressLine4_Region"].ToString();
if (ds.Tables[0].Rows[0]["County"] != DBNull.Value)
{
//Datasource is added only when values are being added to allow for alterations to be made
//Allows for records with older dropdown values no longer selectable to be visible
String strConnString = ConfigurationManager.ConnectionStrings["OepdSQLConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
con.ConnectionString = strConnString;
SqlCommand cmd = new SqlCommand();
SqlCommand cmdPop = new SqlCommand();
cmd.CommandText = "Select County from DropdownCounty";
cmd.Connection = con;
con.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
con.Close();
//String builder to gather records that are currently active
StringBuilder currentid = new StringBuilder();
for (int i = dt.Rows.Count - 1; i >= 0; i--)
{
DataRow dr = dt.Rows[i];
currentid.AppendLine(string.Join(",", dr.ItemArray));
}
//convert stringbuilder to string
var output = currentid.ToString();
// Creates new StringReader instance from System.IO
using (StringReader reader = new StringReader(output))
{
// Loop over the lines in the string.
int count = 0;
string line;
while ((line = reader.ReadLine()) != null)
{
count++;
if (line == (ds.Tables[0].Rows[0]["County"].ToString()))
cmdPop.CommandText = " Select * From DropdownCounty";
}
}
if (cmdPop.CommandText == "")
cmdPop.CommandText = " Select * From DropdownCounty";
cmdPop.Connection = con;
con.Open();
DataTable dtValues = new DataTable();
dtValues.Load(cmdPop.ExecuteReader());
con.Close();
dpdCounty.DataSource = dtValues;
dpdCounty.DataTextField = "County";
dpdCounty.DataValueField = "CountyID";
dpdCounty.DataBind();
dpdCounty.SelectedValue = ds.Tables[0].Rows[0]["CountyID"].ToString();
}
PostCode.Text = ds.Tables[0].Rows[0]["PostCode"].ToString();
HomeTelNumber.Text = ds.Tables[0].Rows[0]["HomeTelNumber"].ToString();
MobileTelNumber.Text = ds.Tables[0].Rows[0]["MobileTelNumber"].ToString();
WorkTelNumber.Text = ds.Tables[0].Rows[0]["WorkTelNumber"].ToString();
PatientEmail.Text = ds.Tables[0].Rows[0]["Email"].ToString();
PatientNotes.Text = ds.Tables[0].Rows[0]["Notes"].ToString();
//Sets the color of the text box depedning if a value has been entered
string hex = "#F0F8FF";
if (txtDateOfBirth.Text != "dd/mm/yyyy")
txtDateOfBirth.ForeColor = System.Drawing.Color.Black;
else
txtDateOfBirth.BackColor = System.Drawing.ColorTranslator.FromHtml(hex);
if (ConsentGivenDate.Text != "dd/mm/yyyy")
ConsentGivenDate.ForeColor = System.Drawing.Color.Black;
else
ConsentGivenDate.BackColor = System.Drawing.ColorTranslator.FromHtml(hex);
}
//If the dataset is empty this is executed instead
catch (Exception fe)
{
lblErrors.Text = "New Record Successfully Started!";
//calls the poup to display a notification
dvMsg.Visible = true;
lblMsg.Text = "" + lblErrors.Text;
}
}
//Not required as this label has been replaced with a popup, still used to store message that will be displayed
lblErrors.Visible = true;
//Load the initial data from the session once
//***Custom error messages below***//
//Used to pull error message if someone else has already updated the data first
if (Session["ex"] != null)
{
var msg = Session["ex"].ToString();
//Message to be displayed
if (msg == "Error")
lblErrors.Text = "Update Failed! Someone has already made changes!";
else
lblErrors.Text = "Unable to update HC Number!";
//calls the popup to display a notification
dvMsg.Visible = true;
lblMsg.Text = "" + lblErrors.Text;
//required to prevent error message appearing everytime the page loads
Session["ex"] = null;
}
//As the page refreshes when a new record is added to allow the master page to display the new records details this is required to pull
//forward the success message to inform the user that the record has been added and the page has not just refreshed
if (Session["NewRecordAdded"] != null)
{
//Message to be displayed
lblErrors.Text = "Record Succesfully Added!";
//calls the popup to display a notification
dvMsg.Visible = true;
lblMsg.Text = "" + lblErrors.Text;
//required to prevent error message appearing everytime the page loads
Session["NewRecordAdded"] = null;
}
//Error when trying to find record that does not exist
if (Session["FindRecordError"] != null)
{
string a = Session["FindRecordError"].ToString();
//Message to be displayed
if (a == "Unable to locate")
lblErrors.Text = "Unable to find record!";
else
lblErrors.Text = "Full HC Number required!";
//calls the popup to display a notification
dvMsg.Visible = true;
lblMsg.Text = "" + lblErrors.Text;
//required to prevent error message appearing everytime the page loads
Session["FindRecordError"] = null;
}
if (Session["PersonalDeatilsSave"] != null)
{
//only if an update has occured
lblErrors.Text = "Save Successful!";
//calls the popup to display a notification
dvMsg.Visible = true;
lblMsg.Text = "" + lblErrors.Text;
//required to prevent error message appearing everytime the page loads
Session["PersonalDeatilsSave"] = null;
}
}
protected void gvAppointmentSearch_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet ds = new DataSet();
int index = gvAppointmentSearch.SelectedIndex;
string strConString = ConfigurationManager.ConnectionStrings["OepdSQLConnectionString"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConString);
myConnect.ConnectionString = strConString;
string strCommandText = "prcPersonalSelectedByPatientIdAppointmentRetrieve";
try
{
SqlCommand sqlCmd = new SqlCommand(strCommandText, myConnect);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.Add(new SqlParameter("#PatientNumber", gvAppointmentSearch.DataKeys[index].Value.ToString()));
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlCmd;
da.Fill(ds, "personal");
//Needed to reset the clinical eval page for newly selected patient
Session["NDS"] = null;
}
catch (Exception fe)
{
lblMoreErrors.Text = "Error: " + fe.Message;
}
try
{
//Assigns the selected patients details to the dataset and redirects the user to the personal page
Session["DS"] = ds;
Response.Redirect("~/UserPages/PatientAppointment.aspx");
}
catch (Exception er)
{
lblErrors.Text = "Error: " + er.Message;
}
}
//Tells the gridview what to do when the page change is selected
protected void OnPaging(object sender, GridViewPageEventArgs e)
{
this.DataBindSearch();
gvAppointmentSearch.PageIndex = e.NewPageIndex;
gvAppointmentSearch.DataBind();
}
protected void DataBindSearch()
{
DataSet ds = new DataSet();
string strConString = ConfigurationManager.ConnectionStrings["OepdSQLConnectionString"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConString);
myConnect.ConnectionString = strConString;
string strCommandText = "prcPersonalSelectedByPatientIdAppointmentSelect";
try
{
SqlCommand sqlCmd = new SqlCommand(strCommandText, myConnect);
sqlCmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlCmd;
da.Fill(ds, "personal");
gvAppointmentSearch.DataSource = ds;
//Finally, all results matching the criteria will be placed into the gridview
gvAppointmentSearch.DataBind();
DataTable dt = new DataTable();
da.Fill(dt);
Session["CurrentData"] = dt;
//Counts the number of results found
lblResults.Text = "Results Found: " + ds.Tables.Cast<DataTable>().Sum(x => x.Rows.Count).ToString();
}
catch (Exception fe)
{
lblErrors.Text = "Error: " + fe.Message;
}
}
}
SQL Stored Procedure
ALTER PROCEDURE [dbo].[prcPersonalSelectedByPatientIdAppointmentSelect]
#PatientNumber int
AS
SELECT
[dbo].[Appointments].[AppointmentDate] as AppointmentDate
,dbo.Appointments.AppointmentTime as AppointmentTime
,[dbo].[DropdownReferredBy].[ReferredBy] as Consultant
,[dbo].[DropdownAttended].[ByAttendance] as ByAttendance
,dbo.Appointments.AppointmentNumber as AppointmentNumber
FROM [dbo].[PATIENTS]
LEFT JOIN dbo.Appointments on dbo.PATIENTS.PatientNumber = dbo.Appointments.PatientNumber
LEFT JOIN [dbo].[DropdownReferredBy] on dbo.Appointments.ReferredBy = [dbo].[DropdownReferredBy].ReferredBy
LEFT JOIN [dbo].[DropdownAttended] on dbo.Appointments.ByAttendance = dbo.DropdownAttended.ByAttendance
WHERE dbo.PATIENTS.PatientNumber LIKE #PatientNumber
ORDER BY AppointmentNumber ASC;
To add to all this, this page takes its data from another gridview with a connecting stored procedure.
Thanks in advance and sorry if I've done something very silly!!!
In your DataBindSearch() method, you are not providing a value for the #PatientNumber parameter. You need to specify that parameter and give it a value like you do further up in your code.
Also, while I have your attention, you should really be putting your SqlConnection and SqlCommand objects in using statements.
protected void DataBindSearch()
{
DataSet ds = new DataSet();
string strConString = ConfigurationManager.ConnectionStrings["OepdSQLConnectionString"].ConnectionString;
string strCommandText = "prcPersonalSelectedByPatientIdAppointmentSelect";
using (SqlConnection myConnect = new SqlConnection(strConString))
using (SqlCommand sqlCmd = new SqlCommand(strCommandText, connect))
{
try
{
SqlCommand sqlCmd = new SqlCommand(strCommandText, myConnect);
sqlCmd.CommandType = CommandType.StoredProcedure;
//You need to add the parameter before you call da.Fill()
sqlCmd.Parameters.Add(new SqlParameter("#PatientNumber", /*Parameter Value*/));
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlCmd;
da.Fill(ds, "personal");
gvAppointmentSearch.DataSource = ds;
//Finally, all results matching the criteria will be placed into the gridview
gvAppointmentSearch.DataBind();
DataTable dt = new DataTable();
da.Fill(dt);
Session["CurrentData"] = dt;
//Counts the number of results found
lblResults.Text = "Results Found: " + ds.Tables.Cast<DataTable>().Sum(x => x.Rows.Count).ToString();
}
catch (Exception fe)
{
lblErrors.Text = "Error: " + fe.Message;
}
}
}
I have 3 dropdownlist: select year, select make, select model. Upon select model the results should appear in a gridview. My tables are:
Makes with [(pk)MakeID, MakeName]; Models with [(pk)ModelID, Make_ID, ModelYear, ModelName]; and Wipers with [(pk)WiperID, Model_ID, Description, Emplacement, Price]. When I step through debug, I see 6 counts of records found, but I do not see it in gridview
I've looked at these for help, but no answers
ASP.net DropDownList populates GridView
Binding gridview with arraylist asp.net/c#
My Default.aspx
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div id="wrapper" align="center">
<asp:DropDownList ID="ddlYear" runat="server"
AutoPostBack="true" OnSelectedIndexChanged="Year_Changed">
</asp:DropDownList>
<asp:DropDownList ID="ddlMake" runat="server"
AutoPostBack="true" OnSelectedIndexChanged="Make_Changed">
</asp:DropDownList>
<asp:DropDownList ID="ddlModel" runat="server"
AutoPostBack="true"
OnSelectedIndexChanged="Get_Wipers_By_Model">
</asp:DropDownList>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<asp:GridView ID="grdWiperList" runat="server">
</asp:GridView>
</form>
My Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Year drop down list is populated on page load
string query = "SELECT DISTINCT ModelYear FROM Models";
string connectionString = ConfigurationManager.ConnectionStrings["wiperConnectionString"].ToString();
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = conn;
conn.Open();
ddlYear.DataSource = cmd.ExecuteReader();
ddlYear.DataValueField = "ModelYear";
ddlYear.DataBind();
conn.Close();
}
}
ddlYear.Items.Insert(0, new ListItem("Select Year", "0"));
ddlMake.Enabled = false;
ddlModel.Enabled = false;
ddlMake.Items.Insert(0, new ListItem("Select Make", "0"));
ddlModel.Items.Insert(0, new ListItem("Select Model", "0"));
}
}
private void BindDropDownList(DropDownList ddl, string query, string text, string value, string defaultText)
{
string connectionString = ConfigurationManager.ConnectionStrings["wiperConnectionString"].ToString();
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = conn;
conn.Open();
ddl.DataSource = cmd.ExecuteReader();
ddl.DataTextField = text;
ddl.DataValueField = value;
ddl.DataBind();
conn.Close();
}
}
ddl.Items.Insert(0, new ListItem(defaultText, "0"));
}
protected void Year_Changed(object sender, EventArgs e)
{
//the Makes drop down list is populated on OnSelectedIndexChange event of the Year_Changed event
ddlMake.Enabled = false;
ddlModel.Enabled = false;
ddlMake.Items.Clear();
ddlModel.Items.Clear();
ddlMake.Items.Insert(0, new ListItem("Select Make", "0"));
ddlModel.Items.Insert(0, new ListItem("Select Model", "0"));
int yearId = int.Parse(ddlYear.SelectedItem.Value);
if (yearId > 0)
{
string query = string.Format("SELECT DISTINCT MakeID, MakeName FROM Makes JOIN Models ON Make_ID = MakeID WHERE ModelYear = {0}", yearId);
BindDropDownList(ddlMake, query, "MakeName", "MakeID", "Select Make");
ddlMake.Enabled = true;
}
}
protected void Make_Changed(object sender, EventArgs e)
{
ddlModel.Enabled = false;
ddlModel.Items.Clear();
ddlModel.Items.Insert(0, new ListItem("Select Model", "0"));
int yearID = int.Parse(ddlYear.SelectedItem.Value);
int makeId = int.Parse(ddlMake.SelectedItem.Value);
if (makeId > 0)
{
string query = string.Format("SELECT ModelID, ModelName FROM Models WHERE ModelYear = {0} AND Make_ID = {1}", yearID, makeId);
BindDropDownList(ddlModel, query, "ModelName", "ModelID", "Select Model");
ddlModel.Enabled = true;
}
}
protected void Get_Wipers_By_Model(object sender, EventArgs e)
{
grdWiperList.DataSource = Connection.GetWipersByModel
(!IsPostBack ? "%" : ddlModel.SelectedValue);
grdWiperList.DataBind();
}
}
My Connection.cs
public static ArrayList GetWipersByModel(string modelType)
{
ArrayList listResults = new ArrayList();
string query = string.Format
("SELECT * FROM Wipers WHERE Model_ID LIKE '{0}'", modelType);
try
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = query;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
int wiperID = reader.GetInt32(0);
int model_id = reader.GetInt32(1);
string description = reader.GetString(2);
string itemNo = reader.GetString(3);
string emplacement = reader.GetString(4);
decimal price = reader.GetDecimal(5);
Wipers wipers = new Wipers(wiperID, model_id, description, itemNo, emplacement, price);
listResults.Add(wipers);
}
}
finally
{
conn.Close();
}
return listResults;
}
I think this because the updatePanel control try to add trigger between UpdatePanel control and DropDownList Control
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>
I dont do asp.net so this is a learning curve for me and a little stuck with something that i know should be easy if you know how so apologies in advance:
Below is the C#:
rptListingAllMandatoryCourses.DataSource = listingAllMandatoryCourses();
rptListingAllMandatoryCourses.DataBind();
public DataSet listingAllMandatoryCourses()
{
DataSet dataSet = new DataSet();
User user = (User)Context.Items["CurrentUser"];
SqlConnection selectConnection = new SqlConnection(ConfigurationSettings.AppSettings["DBConnectStr"]);
SqlDataAdapter adapter = new SqlDataAdapter("dbo.procCataloguesGetAllCoursesByCategory", selectConnection);
adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
// get results
adapter.SelectCommand.Parameters.Add("#FilterByDomain", SqlDbType.Bit).Value = 0;
if (user.Domain.Guid != Guid.Empty)
{
adapter.SelectCommand.Parameters.Add("#DomainID", SqlDbType.UniqueIdentifier).Value = user.Domain.Guid;
}
adapter.SelectCommand.Parameters.Add("#Limit", SqlDbType.Int).Value = 5;
adapter.SelectCommand.Parameters.Add("#FilterByDomain", SqlDbType.Bit).Value = 0;
adapter.SelectCommand.Parameters.Add("#Culture", SqlDbType.VarChar, 6).Value = "en-GB";
adapter.SelectCommand.Parameters.Add("#IsEnabled", SqlDbType.Bit).Value = null;
adapter.SelectCommand.Parameters.Add("#DomainAdminID", SqlDbType.UniqueIdentifier).Value = null;
adapter.SelectCommand.Parameters.Add("#Category", SqlDbType.UniqueIdentifier).Value = "Carousel";
adapter.SelectCommand.Parameters.Add("#UserID", SqlDbType.UniqueIdentifier).Value = null;
try
{
dataSet = new DataSet();
adapter.Fill(dataSet);
}
catch (Exception exception)
{
dataSet.Dispose();
dataSet = null;
LMS_DB.LMS_DB.LogErrorEvent(exception.Message, AuditEntryType.CatalogueCoursesGetCourses);
}
finally
{
if (selectConnection.State == ConnectionState.Open)
{
selectConnection.Close();
}
}
return dataSet;
}
protected void rptListingAllMandatoryCourses_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
DataRowView row = (DataRowView)e.Item.DataItem;
}
Frontend part:
<asp:Repeater ID="rptListingAllMandatoryCourses" runat="server" OnItemDataBound="rptListingAllMandatoryCourses_ItemDataBound">
<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem, "CourseTitle")%>
</ItemTemplate>
</asp:Repeater>
Page loads fine with no errors but i cannot see any data.... ive checked the procedure and i can see data coming back for CourseTitle but does not seem to be passing to the aspx template? any ideas anyone?
screenshot with the results when i run DB query in DB
Thanks
I changed this to use ListView instead of a Repeater and worked great!