This is my first post here and I am new to programming. Right now, I am trying to changing column name in the DataTable which the data is fetch from the sql database. After I changing the column name using a foreach loop, it appears that after i change the column name of the datatable, the program crash right after I bind it to the gridview.
the error occur
Any idea what is causing the error?
C# code behind:
//custom query generator
Session["query"] = db.generate_query(parameter1, parameter2, parameter3, parameter4);
//connecting sql
SqlConnection conn = new SqlConnection("Data Source=USER-PC;Initial Catalog=ISMS;Integrated Security=True");
SqlCommand cmd1 = new SqlCommand(Session["query"].ToString(),conn);
SqlDataAdapter sdal = new SqlDataAdapter(cmd1);
//when search is needed
dt_table = new DataTable();
sdal.Fill(dt_table);
// dataTable.Columns["ExistingColumnName"].ColumnName = "regnum";
//renaming column in datatable
foreach (DataColumn dtclm in dt_table.Columns) {
dt_table.Columns[dtclm.ToString()].ColumnName = dt_table.Columns[dtclm.ToString()].ColumnName.ToString().Replace("_"," ");
}
staff_attendance_gridview.Visible = true;
staff_attendance_gridview.DataSource = dt_table;
staff_attendance_gridview.DataBind();
result_message.Text = dt_table.Rows.Count.ToString() + " rows in the table";
the aspx file:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="admin_attendance_.aspx.cs" Inherits="ISMS.admin_attendance" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<!--start container box-->
<div id="container_box">
<div id="text">
<asp:Label runat="server" ID="welcome_message" /><br />
<br />
<!--search bar-->
<p>
<br />
Employee ID: <asp:TextBox runat="server" ID="employee_search" Text="" /><br />
<br />
Attendance ID: <asp:TextBox runat="server" ID="attendance_ID_text_box" Text="" /><br />
<br />
fill up both attendance ID and Employee ID and click delete to delete certain record.<br />
<br />
<asp:Button ID="search_btn" runat="server" Text="search" OnClick="search_btn_Click" />
<asp:Button ID="clock_in_or_out_btn" runat="server" Text="clock in/out" OnClick="clock_in_or_out_btn_Click" />
<asp:Button ID="delete_button" runat="server" Text="delete" OnClick="delete_button_Click" />
<br />
</p>
<!--gridview-->
<hr />
<br />
<div id="gridview">
<asp:GridView runat="server" ID="staff_attendance_gridview" OnPageIndexChanging="gridview_PageIndexChanging" AutoGenerateColumns="true" DataKeyNames="Attendance_id" >
</asp:GridView>
</div>
<!--end gridview-->
<p>
<!--validator-->
<asp:RegularExpressionValidator ID="employee_search_validator" runat="server"
ErrorMessage="Invalid searching citeria. Only exactly 8 numbers is allowed."
ControlToValidate="employee_search"
ValidationExpression="^[0-9]{8}$" /><br />
<br />
</p>
<br />
<!--hyperlink to main menu-->
<asp:Label runat="server" ID="result_message" /><br />
<a href="admin.aspx" >Main menu</a>
</div>
</div>
<!--end container box-->
</asp:Content>
Database table structure
You have an attribute in your GridView that refers to a column Attendance_id. That must match the updated name of your column Attendance id.
I've corrected your code below to properly handle IDisposable and remove overly complex bits.
Session["query"] = db.generate_query(parameter1, parameter2, parameter3, parameter4);
using(SqlConnection conn = new SqlConnection("Data Source=USER-PC;Initial Catalog=ISMS;Integrated Security=True"))
{
using(SqlCommand cmd1 = new SqlCommand(Session["query"].ToString(), conn))
{
using(SqlDataAdapter sdal = new SqlDataAdapter(cmd1))
{
dt_table = new DataTable();
sdal.Fill(dt_table);
}
}
}
foreach (DataColumn column in dt_table.Columns)
{
column.ColumnName = column.ColumnName.Replace("_", " " );
}
staff_attendance_gridview.Visible = true;
staff_attendance_gridview.DataSource = dt_table;
staff_attendance_gridview.DataBind();
result_message.Text = dt_table.Rows.Count + " rows in the table";
Related
I have a DataList in ASP.NET that brings me the products from the "Products" table, so with the "Eval" statement I assign the product ID:
<asp:TextBox ID="idProductoText" runat="server" type="hidden" value='<%# Eval("PRO_ID") %>'></asp:TextBox>
So in my C# code I need to get the value of that TextBox by its ID, for example an idProductText.Text.Trim(); , but for some reason it doesn't work, any solution? I leave the complete DataList below.
Code to fill the DataList:
public void loadStockProducts()
{
OracleConnection connection = new OracleConnection(with);
OracleCommand command = new OracleCommand("SHOW_PRODUCTS_BUY", connection);
command.CommandType = System.Data.CommandType.StoredProcedure;
command.Parameters.Add("registers", OracleDbType.RefCursor).Direction = ParameterDirection.Output;
OracleDataAdapter d = new OracleDataAdapter();
d.SelectCommand = command;
DataTable dt = new DataTable();
d.Fill(dt);
DataList1.DataSource = dt;
DataList1.DataBind();
connection.Close();
}
Full DataList in ASP.NET
<asp:DataList ID="DataList1" runat="server">
<ItemTemplate>
<div class="card mb-6" style="max-width: 1400px">
<div class="row g-0">
<div class="col-md-4">
<img
src="../../img/armchair.jpg"
class="img-fluid rounded-start"
alt="product" />
</div>
<div class="col-lg-5 m-4 form-floating">
<div class="card-body">
<!-- THE PRODUCT ID IS HIDDEN, IT WILL ONLY BE USED TO ADD TO CART -->
<asp:TextBox ID="idProductoText" runat="server" type="hidden" value='<%# Eval("PRO_ID") %>'></asp:TextBox>
<asp:Label ID="PRO_NAMELabel" class="card-title" runat="server" Text='<%# Eval("PRO_NAME") %>' Font-Bold="true" Font-Size="Large" Visible="True" />
<br />
<br />
Q<asp:Label ID="PRO_PRICELabel" class="card-text" runat="server" Text='<%# Eval("PRO_PRICE") %>' Font-Size="Large" />
<br />
<br />
<div class="input-group">
<asp:Button ID="moreInformation" runat="server" Text="More Information" class="btn btn-dark m-2" />
<asp:TextBox ID="quantidadBuy" runat="server" type="number" class="form-control m-2" placeholder="Quantity to Buy"></asp:TextBox>
<asp:Button ID="addCart" runat="server" Text="Add to Cart" class="btn btn-success m-2"/ OnClick="addCart_Click"/>
</div>
</div>
</div>
</div>
</div>
<br />
</ItemTemplate>
</asp:DataList>
Ok, while there are some events of the data list, you can just grab and get all the information you need/want from that button click you have.
However, before we write that code, I see you need a database row PK id, so, I suggest you remove this:
<!-- THE PRODUCT ID IS HIDDEN, IT WILL ONLY BE USED TO ADD TO CART -->
<asp:TextBox ID="idProductoText" runat="server"
type="hidden" value='<%# Eval("PRO_ID") %>'></asp:TextBox>
Assuming PRO_ID is the PK database id, then we really don't want to have that information in the markup - (even hidden).
So, use the so called "data keys" feature. You COULD leave the above, but remove it - we really don't need it.
So, in datalist, add this setting:
<asp:DataList ID="DataList1" runat="server" DataKeyField = "PRO_ID" >
Ok, so now the click event for the button.
Say we have this button:
<asp:Button ID="cmdView" runat="server" Text="View" CssClass="btn"
OnClick="cmdView_Click" />
Code behind:
protected void cmdView_Click(object sender, EventArgs e)
{
Button cmdView = sender as Button;
DataListItem gRow = cmdView.NamingContainer as DataListItem;
// get row index
Debug.Print("row click = " + gRow.ItemIndex.ToString());
// get database primary key (data keys)
int? PkID = DataList1.DataKeys[gRow.ItemIndex] as int?;
Debug.Print("Database PK id = " + PkID);
// get value of single control - say hotel label called
Label lHotelName = gRow.FindControl("HotelNameLabel") as Label;
Debug.Print("Hotel name = " + lHotelName.Text);
}
Output:
So note several things:
We grab/get current row - naming container. This works for Gridview, repeater, listview - quite much all of the data bound types of controls.
From that row, then we can get:
Row index -
From Row index, we reference into data keys. Note that datalist ONLY supports ONE data key, so in MOST cases, we have to do this .DataKeys[ some index]["SOME KEY"]
But datalist is a exception - only one key, so .DataKeys[some index] is all you require.
And to pull controls out, use .FindControl as I show above.
FYI: debug.print - this requires using System.Diagnostics;
(and I have my outputs re-directed to Immediate window).
My intention is to populate textbox controls on an ASPX page using a SQL Inner Join. One textbox control(txtContactNum) is to be populated from my CompanyContacts table, while the other two textboxes(txtCity, txtURL) are to be populated from the Companies table.
Here are the SQL Inner Join statements I have tried in the btnSelectCompany Event Handler:
comm = new SqlCommand("Select CompanyContacts.ContactNum, Companies.CompanyNum, Companies.CompanyName, Companies.City, Companies.URL FROM Companies INNER JOIN CompanyContacts ON CompanyNum = #CompanyNum;", conn);
comm = new SqlCommand("Select Companies.CompanyNum, Companies.CompanyName, Companies.City, Companies.URL CompanyContacts.ContactNum FROM Companies, CompanyContacts WHERE CompanyNum = #CompanyNum", conn);
comm = new SqlCommand("Select CompanyName, City, URL FROM Companies WHERE CompanyNum = #CompanyNum", conn);
<asp:Calendar ID="calDateOfPosting" SelectionMode="Day" ShowGridLines="True" OnSelectionChanged="DateSelection_Change" runat="server">
<SelectedDayStyle BackColor="Yellow" ForeColor="Red"></SelectedDayStyle>
</asp:Calendar>
<span class="widelabel">Date Of Posting:</span>
<asp:TextBox ID="txtDateOfPosting" runat="server" />
<br />
<br />
<span class="widelabel">Company:</span>
<asp:DropDownList ID="ddlCompanies" runat="server">
</asp:DropDownList>
<asp:Button ID="btnSelectCompany" Text="Select Company" runat="server"
onclick="btnSelectCompany_Click" />
<br />
<br />
<span class="widelabel">Contact Number:</span>
<asp:TextBox ID="txtContactNum" runat="server" ReadOnly="True" BackColor="#CCCCCC" />
<br />
<br />
<span class="widelabel">Job Type:</span>
<asp:DropDownList ID="ddlJobType" runat="server">
<asp:ListItem>Software/Development</asp:ListItem>
<asp:ListItem>Networking</asp:ListItem>
</asp:DropDownList>
<br />
<br />
<span class="widelabel">Posting Source:</span>
<asp:DropDownList ID="ddlPostingSource" runat="server">
<asp:ListItem>Select Posting Source</asp:ListItem>
<asp:ListItem>NEIT</asp:ListItem>
<asp:ListItem>Web Search Engines</asp:ListItem>
<asp:ListItem>Tech Collective</asp:ListItem>
</asp:DropDownList>
<br />
<br />
<span class="widelabel">Description:</span>
<asp:TextBox ID="txtDescription" runat="server" />
<br />
<br />
<span class="widelabel">City:</span>
<asp:TextBox ID="txtCity" runat="server" ReadOnly="True" BackColor="#CCCCCC" />
<br />
<br />
<span class="widelabel">URL:</span>
<asp:TextBox ID="txtURL" runat="server" ReadOnly="True" BackColor="#CCCCCC" />
<br />
<br />
<span class="widelabel">Attachment:</span>
<%--<asp:TextBox ID="TextBox1" runat="server" />--%>
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<br />
<span class="widelabel">Cover Letter Submitted?:</span>
<asp:DropDownList ID="ddlCoverLetter" OnSelectedIndexChanged="Letter" AutoPostBack="true" runat="server">
<asp:ListItem>No</asp:ListItem>
<asp:ListItem>Yes</asp:ListItem>
</asp:DropDownList>
<br />
<br />
<asp:Panel ID="pnlLetter" runat="server">
<p><b>Date Cover Letter Submitted:</b></p>
<asp:Calendar ID="calCLDateSubmitted" SelectionMode="Day" ShowGridLines="True" OnSelectionChanged="CLDateSubmitted_Change" runat="server">
<SelectedDayStyle BackColor="Yellow" ForeColor="Red"></SelectedDayStyle>
</asp:Calendar>
<span class="widelabel">Date Of Submission:</span>
<asp:TextBox ID="txtCLDateSubmitted" runat="server" />
</asp:Panel>
<span class="widelabel">Resume Submitted?:</span>
<asp:DropDownList ID="ddlResume" OnSelectedIndexChanged="Resume" AutoPostBack="true" runat="server">
<asp:ListItem>No</asp:ListItem>
<asp:ListItem>Yes</asp:ListItem>
</asp:DropDownList>
<br />
<br />
<asp:Panel ID="pnlResume" runat="server">
<p><b>Date Resume Submitted:</b></p>
<asp:Calendar ID="calRDateSubmitted" SelectionMode="Day" ShowGridLines="True" OnSelectionChanged="RDateSubmitted_Change" runat="server">
<SelectedDayStyle BackColor="Yellow" ForeColor="Red"></SelectedDayStyle>
</asp:Calendar>
<span class="widelabel">Date Of Submission:</span>
<asp:TextBox ID="txtRDateSubmitted" runat="server" />
</asp:Panel>
<br />
<br />
<span class="widelabel">Comments:</span>
<asp:TextBox ID="txtComments" TextMode="MultiLine" runat="server"></asp:TextBox>
<br />
<br />
Below is the C# business logic
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
public partial class JobPostings_JobPostings : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
pnlLetter.Visible = false;
pnlResume.Visible = false;
LoadCompanies();
}
}
private void LoadCompanies()
{
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
string connectionString = ConfigurationManager.ConnectionStrings["jobSearchDB"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("Select CompanyNum,CompanyName FROM Companies", conn);
try
{
conn.Open();
reader = comm.ExecuteReader();
ddlCompanies.DataSource = reader;
ddlCompanies.DataValueField = "CompanyNum";
ddlCompanies.DataTextField = "CompanyName";
ddlCompanies.DataBind();
reader.Close();
} // End of Try Block
catch (Exception ex)
{
lblErrorLabel.Text = "The Following Errors ocurred during the Data Read process: ";
lblErrorLabel.Text += ex.Message.ToString();
}
finally
{
conn.Close();
} // End of Finally Block
ClearFormClass clearForm = new ClearFormClass();
clearForm.ClearWebFormControls1(pnlAddJobPosting);
} // End of LoadCompanies()
protected void btnSelectCompany_Click(object sender, EventArgs e)
{
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
string connectionString = ConfigurationManager.ConnectionStrings["jobSearchDB"].ConnectionString;
conn = new SqlConnection(connectionString);
// Create a SQL Query with an Inner Join for tables Companies and CompanyContacts so that CITY and URL can be returned from Companies, and ContactNum can be returned from CompanyContacts
// I have listed the SQL Queries which I have tried below.
comm = new SqlCommand("Select CompanyContacts.ContactNum, Companies.CompanyNum, Companies.CompanyName, Companies.City, Companies.URL FROM Companies INNER JOIN CompanyContacts ON CompanyNum = #CompanyNum;", conn);
comm = new SqlCommand("Select Companies.CompanyNum, Companies.CompanyName, Companies.City, Companies.URL CompanyContacts.ContactNum FROM Companies, CompanyContacts WHERE CompanyNum = #CompanyNum", conn);
comm = new SqlCommand("Select CompanyName, City, URL FROM Companies WHERE CompanyNum = #CompanyNum", conn);
comm.Parameters.Add("#CompanyNum", System.Data.SqlDbType.Int);
comm.Parameters["#CompanyNum"].Value = ddlCompanies.SelectedItem.Value;
try
{
conn.Open();
reader = comm.ExecuteReader();
if (reader.Read())
{
txtContactNum.Text = reader["ContactNum"].ToString();
txtCity.Text = reader["City"].ToString();
txtURL.Text = reader["URL"].ToString();
} // End of IF Block
reader.Close();
btnClear.Enabled = true;
btnCancel.Enabled = true;
} // End of Try Block
catch (Exception ex)
{
lblErrorLabel.Text = "Error Loading The Company Information For The Job Posting.<br />";
lblErrorLabel.Text += ex.Message.ToString();
} // End of Catch Block
finally
{
conn.Close();
}
} // End of btnSelectCompany_Click
From comments on the question...
Incorrect syntax near '.'
You have a typo in your query:
Select Companies.CompanyNum, Companies.CompanyName, Companies.City, Companies.URL CompanyContacts.ContactNum FROM ...
Note the missing comma between the last two fields in the SELECT list. Selected fields need to be separated by a comma:
Select Companies.CompanyNum, Companies.CompanyName, Companies.City, Companies.URL, CompanyContacts.ContactNum FROM ...
here ---^
The following SQL statement works. (comm = new SqlCommand("Select Companies.CompanyNum, Companies.City, Companies.URL, CompanyContacts.ContactNum FROM Companies, CompanyContacts WHERE Companies.CompanyNum = #CompanyNum", conn);)It is listed as the second SQL statement in my abstract at the top of this post. The reason it did not work initially was because I was pointing to a database that did not contain any data in the CompanyContacts table.
In .aspx page , I’ve taken Label Control in order to display question form the database,
4 radio buttons in order to display four option related to a particular question, and last but not the least, I’ve used hidden field in which I will store answer of the particular question.
And finally I’ve taken a Button Control, for which I’ve created the onclick event, on which I will perform the operation to generate score.
In .aspx.cs page, on the onclick event of the button, , I’ve fetch the controls form the aspx page using code mentioned below, and further I’ve used if statement in order to see which radio button is active and have store the corresponding value in the varialbe “selans”, using this “selans”, I will compare it with the value of hidden field in order to find whether checked radio button is the correct answer or not, it the answer is correct, i.e value in “selans” matches with the value in hidden field ( the actual answer) and the variable “count” ( initially initialized with value 0) increments accordingly, and all this code is placed in the “for loop” which will execute till the no. of controls in the GridView (you can relate it with the no. of question, as for every record GridView generates new control).
But when I run it I am getting this error :-
DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'Optiont4'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'Optiont4'.
Source Error:
Line 115: <asp:RadioButton ID="rad2" runat="server" Text='<%#Eval("Option2") %>' GroupName="A" />
Line 116: <asp:RadioButton ID="rad3" runat="server" Text='<%#Eval("Option3") %>' GroupName="A" />
Line 117: <asp:RadioButton ID="rad4" runat="server" Text='<%#Eval("Optiont4")%>' GroupName="A" />
Line 118: <asp:HiddenField ID="hf" runat="server" Value='<%#Eval("CorrectAns")%>' />
Line 119:
Source File: e:\Way2Success\Student\Examdemo.aspx Line: 117
Here the error line number is 30 in .aspx page
Have a look at my code. Show me were I am making mistaking and what is the solution.
.aspx :-
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Examdemo.aspx.cs" Inherits="Student_Examdemo" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form2" runat="server">
<div>
<div id="tabs">
<ul>
<li>Tab 1</li>
<li>Tab 2</li>
<li>Tab 3</li>
<li>Tab 4</li>
<li>Tab 5</li>
</ul>
<div id="tabs-1">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%#Eval("Question") %>'></asp:Label>
<br />
<br />
<br />
<asp:RadioButton ID="rad1" runat="server" Text='<%#Eval("Option1") %>' GroupName="A" />
<asp:RadioButton ID="rad2" runat="server" Text='<%#Eval("Option2") %>' GroupName="A" />
<asp:RadioButton ID="rad3" runat="server" Text='<%#Eval("Option3") %>' GroupName="A" />
<asp:RadioButton ID="rad4" runat="server" Text='<%#Eval("Option4") %>' GroupName="A" />
<asp:HiddenField ID="hf" runat="server" Value='<%#Eval("CorrectAns") %>' />
<br />
<br />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div id="tabs-2">
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%#Eval("Question") %>'></asp:Label>
<br />
<br />
<br />
<asp:RadioButton ID="rad1" runat="server" Text='<%#Eval("Option1") %>' GroupName="A" />
<asp:RadioButton ID="rad2" runat="server" Text='<%#Eval("Option2") %>' GroupName="A" />
<asp:RadioButton ID="rad3" runat="server" Text='<%#Eval("Option3") %>' GroupName="A" />
<asp:RadioButton ID="rad4" runat="server" Text='<%#Eval("Optiont4")%>' GroupName="A" />
<asp:HiddenField ID="hf" runat="server" Value='<%#Eval("CorrectAns")%>' />
<br />
<br />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div id="tabs-3">
Tab 3 Content
</div>
<div id="tabs-4">
Tab 4 Content
</div>
<div id="tabs-5">
Tab 5 Content
</div>
</div>
<input type="button" id="btnPrevious" value="Previous" style = "display:none"/>
<input type="button" id="btnNext" value="Next" />
<asp:Button class="panelButton" runat="server" Text="Finish the exam" ClientIDMode="Static" OnClick="btn_Click" />
<br />
</div>
</form>
</body>
</html>
.aspx.cs :-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
public partial class Student_Examdemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = GetData("SELECT top 2 Question, Option1, Option2, Option3, Option4, CorrectAns, Explanation FROM Questions");
GridView1.DataBind();
GridView2.DataSource = GetData("SELECT top 2 Question, Option1, Option2, Option3, Option4, CorrectAns, Explanation FROM Questions WHERE SectionId=2");
GridView2.DataBind();
private DataSet GetData(string query)
{
string conString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return ds;
}
}
}
}
protected void btn_Click(object sender, EventArgs e)
{
RadioButton r1, r2, r3, r4;
HiddenField hdn;
int count = 0;
int neg = 0;
int total;
int totalf=0;
int totals=0;
int totalt;
int totalfo;
int totalfi;
string selans = "-1";
for (int i = 0; i < GridView1.Rows.Count; i++)
{
r1 = (RadioButton)GridView1.Rows[i].Cells[0].FindControl("rad1");
r2 = (RadioButton)GridView1.Rows[i].Cells[0].FindControl("rad2");
r3 = (RadioButton)GridView1.Rows[i].Cells[0].FindControl("rad3");
r4 = (RadioButton)GridView1.Rows[i].Cells[0].FindControl("rad4");
hdn = (HiddenField)GridView1.Rows[i].Cells[0].FindControl("hf");
if (r1.Checked)
{
selans = r1.Text;
}
else if (r2.Checked)
{
selans = r2.Text;
}
else if (r3.Checked)
{
selans = r3.Text;
}
else if (r4.Checked)
{
selans = r4.Text;
}
if (hdn.Value == selans)
{
count++;
}
else
{
neg--;
}
totalf = count + neg;
}
for (int i = 0; i < GridView2.Rows.Count; i++)
{
r1 = (RadioButton)GridView2.Rows[i].Cells[0].FindControl("rad1");
r2 = (RadioButton)GridView2.Rows[i].Cells[0].FindControl("rad2");
r3 = (RadioButton)GridView2.Rows[i].Cells[0].FindControl("rad3");
r4 = (RadioButton)GridView2.Rows[i].Cells[0].FindControl("rad4");
hdn = (HiddenField)GridView2.Rows[i].Cells[0].FindControl("hf");
if (r1.Checked)
{
selans = r1.Text;
}
else if (r2.Checked)
{
selans = r2.Text;
}
else if (r3.Checked)
{
selans = r3.Text;
}
else if (r4.Checked)
{
selans = r4.Text;
}
if (hdn.Value == selans)
{
count++;
}
else
{
neg--;
}
totals = count + neg;
}
total = totalf + totals;
Session["score"] = total;
}
}
You have a typing error in your GridView2 definition.
<asp:RadioButton ID="rad4" runat="server" Text='<%#Eval("Optiont4")%>' GroupName="A" />
should be
<asp:RadioButton ID="rad4" runat="server" Text='<%#Eval("Option4")%>' GroupName="A" />
I get the following error in a page:
'The name 'DataList1' does not exist in the current context'
Here is my code:
listviewvideo.aspx.cs
private void BindGrid()
{
string strConnString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Id, Name from uploadvideo";
cmd.Connection = con;
con.Open();
DataList1.DataSource = cmd.ExecuteReader();
DataList1.DataBind();
con.Close();
}
}
}
listviewvideo.aspx
<table>
<tr>
<td>
<ASPNetFlashVideo:FlashVideo ID="FlashVideo1" runat="server" Height="500" Width="1050"></ASPNetFlashVideo:FlashVideo>
<asp:FileUpload ID="FileUpload1" runat="server" CssClass="myButton" />
<asp:Button ID="btnupload" runat="server" Text="Upload" OnClick="btnupload_Click" CssClass="myButton" />
<hr />
<asp:DataList ID="DataList1" Visible="true" runat="server" AutoGenerateColumns="false" RepeatColumns="2" CellSpacing="5">
<ItemTemplate>
<u>
<%# Eval("Name") %>
</u>
<a class="player" style="height:300px; width:300px; display:block" href='<%# Eval("Id","FileCS.ashx?Id={0}") %>'></a>
</ItemTemplate>
</asp:DataList>
</td>
</tr>
</table>
I get the following error in a page:
'The name 'DataList1' does not exist in the current context'
You might get this error. There 3 solutions for this
Save your project and close the Solution, close the IIS Express also. And check whether it works or not.
Try adding the the datalist by writing below code in your listviewvideo.aspx.designer.cs page of where you are adding the Datalist item.
Check your code behind file name and Inherits property on the #Page directive, make sure they both match.
Also you can have a look here for more clear picture
ID Does not exist in the current context
protected global::System.Web.UI.WebControls.DataList Datalist1;
Hope this helps.
I'm new to c# and I'm trying to build my skills without using any of the wizard tools (eg. login wizard) provided in .net. So far I've been successful in creating a very basic login website.
I'm trying to create a user profile page that will display all the data (first name, last name, etc) of the user logged in.
Text boxes on the page should populate on Page_Load but they are not.
here is the aspx page
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="UserProfile.aspx.cs" Inherits="TimeHub2.UserProfile" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="UserProfile" runat="server">
<div class="header">
<h1>TimeHub</h1>
<ul>
<li>my cards</li>
<li>profile</li>
<li>help</li>
<li><asp:Label runat="server" ID="userloggedin"></asp:Label></li>
<li><asp:button runat="server" id="buttonLogout" text="Log Out" onClick="logOutClick" /></li>
</ul>
</div>
<div>
<label for="username">username</label>
<asp:TextBox runat="server" id="username"></asp:TextBox>
<label for="first_name">first name</label>
<asp:TextBox runat="server" ID="first_name"></asp:TextBox>
<label for="middle_intial">middle initial</label>
<asp:TextBox runat="server" ID="middle_intial"></asp:TextBox>
<label for="last_name">last name</label>
<asp:TextBox runat="server" ID="last_name"></asp:TextBox>
</div>
<div>
<label for="star">star</label>
<asp:TextBox runat="server" ID="star"></asp:TextBox>
<label for="rank">rank</label>
<asp:TextBox runat="server" ID="rank"></asp:TextBox>
</div>
<div>
<label for="assignment">assignment</label>
<asp:TextBox runat="server" ID="assignment"></asp:TextBox>
<label for="regular_shift">regular shift</label>
<asp:TextBox runat="server" ID="regular_shift"></asp:TextBox>
</div>
<div>
<label for="contact_phone">contact phone</label>
<asp:TextBox runat="server" ID="contact_phone"></asp:TextBox>
<label for="phone_type">phone type</label>
<asp:DropDownList ID="phone_type" runat="server">
<asp:ListItem>home</asp:ListItem>
<asp:ListItem>cell</asp:ListItem>
</asp:DropDownList>
<label for="email">sfpd email</label>
<asp:TextBox runat="server" ID="email" TextMode="Email"></asp:TextBox>
</div>
<div>
<asp:Button runat="server" ID="save" Text="update profile" />
</div>
</form>
</body>
</html>
Here is the c# code I have written to populate the TextBox "first_name":
protected void Page_Load(object sender, EventArgs e)
{
//show user logged in
if (Session["New"] != null)
{
userloggedin.Text = Session["New"].ToString();
}
//else redirect to login
else
Response.Redirect("Login.aspx");
SqlConnection conn = new SqlConnection(Connection-String);
SqlDataReader profileReader = null;
string userDataQuery = "SELECT * FROM dbo.users WHERE username ='" + userloggedin.Text + "'";
conn.Open();
SqlCommand cmd = new SqlCommand(userDataQuery, conn);
profileReader = cmd.ExecuteReader();
while(profileReader.Read())
{
first_name.Text = profileReader["first_name"].ToString();
}
conn.Close();
}
Thanks for your help
solved my own problem. The issue was in the column names of my database. my naming convention used underscores in the column names, however I omitted the underscore for the column in question. Rather than 'first_name' as it should have been, it was 'first name'.
If You are retrieving Only FirstName then There is no need to use *
try like this
string userDataQuery = "SELECT first_name FROM dbo.users
WHERE username ='" + userloggedin.Text + "'";
while(profileReader.Read())
{
first_name.Text = profileReader["first_name"]==DBNull.Value ? "":
profileReader["first_name"].ToString();
}
Beware of SQL Injection Always Use SqlParameter