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!
Related
After some lengthy experimentation, I discovered that having this line of code on the aspx side:
<EditItemTemplate>
<asp:DropDownList ID="ddl_Project_Owner" runat="server" Width="70px"
DataTextField="Project_Owner" DataValueField="Project_Owner"
SelectedValue='<%# Bind("Project_Owner") %>' >
</asp:DropDownList>
</EditItemTemplate>
caused an index error, but removing the SelectedValue='<%# Bind("Project_Owner") %>' piece allowed the gridview to function properly. The only thing is, when the row goes into edit mode, the dropdown is not filled with the current value. It's blank. I'd like to fill it with the current value.
On the code-behind side, I use this code to fill the dropdown:
protected void DataGrid_ResourceAllocation_EditCommand(object sender, GridViewEditEventArgs e)
{
DataGrid_ResourceAllocation.EditRowStyle.BackColor = System.Drawing.Color.LightYellow;
DataGrid_ResourceAllocation.EditIndex = e.NewEditIndex;
LoadResourceAllocationGrid();
//DataGrid_ResourceAllocation.DataBind();
SqlConnection conn = GetConnection();
int RAC = DataGrid_ResourceAllocation.Rows.Count;
GridViewRow row = DataGrid_ResourceAllocation.Rows[e.NewEditIndex];
//*********************************************************
//******** Fill in all your dropdown lists here ***********
//*********************************************************
DropDownList ddList = row.FindControl("ddl_Project_Owner") as DropDownList;
string ddListVal = ddList.SelectedValue;
//DropDownList ddList = (DropDownList)e.Row.FindControl("ddl_Project_Owner");
if (ddList != null)
{
//bind dropdown-list
string sqlStr = "Select distinct Project_Owner from tblProjectHealth order by Project_Owner";
DataSet ds = new DataSet();
conn.Open();
SqlCommand cmd = new SqlCommand(sqlStr, conn);
SqlDataAdapter ad = new SqlDataAdapter(cmd);
ad.Fill(ds);
ddList.DataSource = ds;
ddList.DataTextField = "Project_Owner";
ddList.DataValueField = "Project_Owner";
ddList.DataBind();
//DataRowView dr = e.Row.DataItem as DataRowView;
//ddList.SelectedItem.Text = dr["category_name"].ToString();
ddList.SelectedValue = ddListVal;
}
}
I tried that "ddListVal" variable because I thought it might work, but it didn't, so you can ignore that.
Can anyone help me get my dropdown to populate with the current value that exists for that field in that record?
This error is due to this : you set selectedValeue befor binding dropdownlist.
you can bind dropdownlist in RowDataBound
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddList= e.Row.FindControl("ddl_Project_Owner") as DropDownList;
if (ddList != null)
{
string sqlStr = "Select distinct Project_Owner from tblProjectHealth order by Project_Owner";
DataSet ds = new DataSet();
conn.Open();
SqlCommand cmd = new SqlCommand(sqlStr, conn);
SqlDataAdapter ad = new SqlDataAdapter(cmd);
ad.Fill(ds);
ddList.DataSource = ds;
ddList.DataTextField = "Project_Owner";
ddList.DataValueField = "Project_Owner";
ddList.DataBind();
}
}
}
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 want to have a label and checkbox for each row in from my query.
I needed to get the number of records from my sql query, but I read that SELECT statements will not work with int numberOfRecords = sqlCmd2.ExecuteNonQuery();. So what should I do instead to get the number of records selected from my query (see code below)?
Is this code enough to do what I need to generate labels and checkboxes from a db? Or am I missing something?
Side Note: I do not want to use the Repeater Control. I have tried it, and it isn't robust enough as I program more complicated pages.
ASP
<table>
<tr>
<td>
<asp:Label ID="LabelFormFields" runat="server" Text="Label"></asp:Label>
</td>
<td>
<asp:CheckBoxList ID="CheckBoxListFormFields" runat="server">
</asp:CheckBoxList>
</td>
</tr>
</table>
C#
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection sqlConn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["Events2"].ConnectionString))
{
sqlConn2.Open();
using (SqlCommand sqlCmd2 = new SqlCommand())
{
sqlCmd2.Connection = sqlConn2;
sqlCmd2.CommandType = System.Data.CommandType.Text;
sqlCmd2.CommandText = string.Format("SELECT DisplayName FROM FormField WHERE EventId = 1 AND Visible = 0 ORDER BY ColumnOrder ASC;");
sqlCmd2.ExecuteNonQuery();
int numberOfRecords = //something here;
using (SqlDataReader sqlReader = sqlCmd2.ExecuteReader())
{
while (sqlReader.Read())
{
for (int i = 0; i < numberOfRecords; i++)
{
var PanelFormFields = new Panel();
var LabelFormFields = new Label();
var ListItemFormFields = new ListItem();
LabelFormFields.Text = sqlReader["DisplayName"].ToString();
CheckBoxListFormFields.Items.Add(new ListItem(sqlReader["DisplayName"].ToString(), "C"));
PanelFormFields.Controls.Add(LabelFormFields);
PanelFormFields.Controls.Add(CheckBoxListFormFields);
}
}
}
sqlConn2.Close();
}
}
}
int numberOfRecords = sqlCmd2.ExecuteNonQuery(); //you will get the record numbers; https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx
But you don't need the numbers here.
your while (sqlReader.Read()) will help to to control the bounds of loop. Based on your description, you don't need this reader. just fill a datatable, then assign it to a datagrid control. as per you want to display a checkbox for each line, you need to make a custom column.
Here is a good sample about how to implement a checkbox and a label in datagrid: http://www.codeproject.com/Articles/7629/Using-CheckBoxes-within-the-DataGrid-control-to-se
use DataTable.Load(IDataReader reader) method to fill a DataTable and then use DataTable.Rows.Count to get number of Records. change your code to something like this:
.
.
sqlCmd2.CommandType = System.Data.CommandType.Text;
sqlCmd2.CommandText = string.Format("SELECT DisplayName FROM FormField WHERE EventId = 1 AND Visible = 0 ORDER BY ColumnOrder ASC;");
int numberOfRecords;
using (System.Data.DataTable dataTable =new System.Data.DataTable())
{
dataTable.Load(sqlCmd2.ExecuteReader());
numberOfRecords = dataTable.Rows.Count;
for (int i = 0; i < dataTable.Rows.Count; i++)
{
System.Data.DataRow dr = dataTable.Rows[i];
var PanelFormFields = new Panel();
var LabelFormFields = new Label();
var ListItemFormFields = new ListItem();
LabelFormFields.Text = dr["DisplayName"].ToString();
CheckBoxListFormFields.Items.Add(new ListItem(dr["DisplayName"].ToString(), "C"));
PanelFormFields.Controls.Add(LabelFormFields);
PanelFormFields.Controls.Add(CheckBoxListFormFields);
}
}
Here is one answer. Please note that I put the code in the Page_Init rather than Page_Load because the Page_Load reloads with every postback and any changes that were not yet written to the database could go away.
protected void Page_Init(object sender, EventArgs e)
{
DataTable dt = GetData();
//int numberOfRecords = dt.Rows.Count;
foreach (DataRow row in dt.Rows)
{
var PanelFormFields = new Panel();
var LabelFormFields = new Label();
var ListItemFormFields = new ListItem();
LabelFormFields.Text = row[0].ToString();
CheckBoxListFormFields.Items.Add(new ListItem(row[0].ToString(), "C"));
PanelFormFields.Controls.Add(LabelFormFields);
PanelFormFields.Controls.Add(CheckBoxListFormFields);
}
}
private DataTable GetData()
{
DataTable dt = new DataTable();
using (SqlConnection sqlConn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["Events2"].ConnectionString))
{
sqlConn2.Open();
string sql = string.Format("SELECT DisplayName FROM FormField WHERE EventId = 1 AND Visible = 0 ORDER BY ColumnOrder ASC;");
using (SqlCommand sqlCmd2 = new SqlCommand(sql, sqlConn2))
{
using (SqlDataAdapter da = new SqlDataAdapter(sqlCmd2))
{
da.Fill(dt);
}
}
}
return dt;
}
Also note that I refactored to use a GetData() method to retrieve the DataTable object and simplify the Page_Init method. I did not close the sqlConn2 object because the using block does this for me. I also used a DataAdapter because it is a simple, fast way to fill a table. Finally, while I kept the numberOfRecords in a commented line to show you how you can get the count, if you need it, it is commented because the foreach loop doesn't need this value.
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?
I have a databound textbox within a gridview which enables the user to easily and quickly bulk update rows. I have tried to use the CustomValidator to validate each textbox against a SQL column but it doesn't behave the way I need it to. The CustomValidator code works properly in the TextChanged event, however it does not behave properly in the ServerValidate event (I understand why). If I leave the code in the TextChanged event handler it still allows the data to be modified when hitting the Update button I created. What can I do to validate each TextBox individually and effectively against the SQL data?
<ItemTemplate>
<asp:TextBox ID="Account" runat="server" AutoPostBack="true" OnTextChanged="Account_TextChanged" Text='<%# Bind("Account") %>'></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server" CssClass="CustomValidator" ValidateEmptyText="false" SetFocusOnError="True" Display="Dynamic" ControlToValidate="Account" OnServerValidate="Validate_ServerValidate" ErrorMessage="Custom Validator"></asp:CustomValidator>
</ItemTemplate>
foreach (GridViewRow row in GridView2.Rows)
{
TextBox Account = row.FindControl("Account") as TextBox;
CustomValidator validator = row.FindControl("CustomValidator1") as CustomValidator;
string sAccount = Account.Text;
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString))
using (SqlDataAdapter da = new SqlDataAdapter("SELECT Account Table WHERE Account = #Account", conn))
{
da.SelectCommand.Parameters.Add("#Account", SqlDbType.VarChar);
da.SelectCommand.Parameters["#Account"].Value = sAccount;
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
validator.IsValid = true;
}
else
{
validator.IsValid = false;
}
}
}
I think you would want to do something like
Front Page:
<asp:TextBox runat="server" ID="txtValidateMe"></asp:TextBox>
<asp:CustomValidator runat="server" id="validateTheTextBox" OnServerValidate="validateTheTextBox_OnServerValidate" ControlToValidate="txtValidateMe"/>
Server Side
protected void Page_Load(object sender, EventArgs e)
{
Page.Validate();
if (Page.IsValid)
{
//do something
}
}
protected void validateTheTextBox_OnServerValidate(object source, ServerValidateEventArgs args)
{
using (var conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString))
using (var da = new SqlDataAdapter("SELECT Account Table WHERE Account = #Account", conn))
{
da.SelectCommand.Parameters.Add("#Account", SqlDbType.VarChar);
da.SelectCommand.Parameters["#Account"].Value = args.Value;
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
}
hope this helps
I was able to get this handled by moving the validation logic out of the ServerValidate Event and into an update buttonclick event.
protected void update_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in SomeGrid.Rows)
{
TextBox SomeTextBox = row.FindControl("SomeTextBox") as TextBox;
CustomValidator validator = row.FindControl("SomeValidator") as CustomValidator;
string Account = SomeTextBox.Text;
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
using (SqlDataAdapter da = new SqlDataAdapter("SELECT Account FROM Account WHERE Account = #Account", conn))
{
da.SelectCommand.Parameters.Add("#Account", SqlDbType.VarChar);
da.SelectCommand.Parameters["#Account"].Value = Account;
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
validator.IsValid = true;
}
else
{
validator.IsValid = false;
}
}
}
}