Error inserting into database - c#

I have a web form which is basically this,
my page has LABELS, BUTTONS, GRIDVIEW, TEXTBOXES
DATA shown came from ANOTHER DATABASE
whenever i try to INSERT into another database (again)
ERROR occurs saying:
An explicit value for the identity column in table 'PO2' can only be
specified when a column list is used and IDENTITY_INSERT is ON.
I am using Sql server
ASPNET CODES:
<table class="col-lg-12">
<tr>
<td class="style5">
Shipping Method</td>
<td class="style6">Shipping Term</td>
<td class="style6">Payment Term</td>
<td class="style4">Delivery Date</td>
<td class="style4">Final Delivery Date</td>
</tr>
<tr>
<td>
<asp:Label ID="lbShippingMethod" runat="server" BorderColor="Black" Font-Size="Larger" /></td>
<td>
<asp:Label ID="lbShippingTerm" runat="server" BorderColor="Black" Font-Size="Larger" /></td>
<td>
<asp:Label ID="lbPaymentTerm" runat="server" BorderColor="Black" Font-Size="Larger" /></td>
<td>
<asp:Label ID="lbDeliveryDate" runat="server" BorderColor="Black" Font-Size="Larger" /></td>
<td>
<asp:Textbox ID="txtDate" runat="server" BorderColor="Black" Font-Size="Larger" type="date" /></td>
</tr>
<tr>
<td>
<br />
<br />
</td>
</tr>
</div>
</table>
<div class="container">
<div class="col-lg-10 pull-right">
<table class="col-lg-12">
<tr>
<td>
PR#</td>
<td class="style2">
Product Name
</td>
<td>Product#</td>
<td>Price</td>
<td>
Quantity
</td>
</tr>
<tr>
<td>
<asp:Label ID="PRID" runat="server" BorderColor="Black" Font-Size="Larger" />
</td>
<td>
<asp:DropDownList ID="ddlName" runat="server" class="form-control"
Width="150px" onselectedindexchanged="ddlName_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
</td>
<td class="style2">
<asp:Label ID="lbProductID" runat="server" Width="90px"></asp:Label>
</td>
<td class="style2">
<asp:Label ID="lbPrice" runat="server"></asp:Label>
</td>
<td>
<asp:TextBox ID="Quantity" runat="server" Width="90px" Type="Number" required></asp:TextBox>
</td>
<td>
<asp:Label ID="Amount" runat="server" Width="90px" Type="Number" required> </asp:Label>
</td>
<div class="pull-right">
<td><asp:Button ID="btnAdd" runat="server" class="btn btn-default"
style="background-color:Silver" text="Add Product" ForeColor="Black"
onclick="btnAdd_Click" />
</td>
</div>
</tr>
</table>
</div>
</div>
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="1000px" HorizontalAlign="Center"
DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="PRID" HeaderText="PRID" SortExpression="PRID" />
<asp:BoundField DataField="ProductID" HeaderText="ProductID"
SortExpression="ProductID" />
<asp:BoundField DataField="ProductName" HeaderText="ProductName"
SortExpression="ProductName" />
<asp:BoundField DataField="Price" HeaderText="Price" SortExpression="Price" />
<asp:BoundField DataField="Quantity" HeaderText="Quantity"
SortExpression="Quantity" />
<asp:BoundField DataField="Amount" HeaderText="Amount"
SortExpression="Amount" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:MyOwnMeatshopConnectionString %>"
SelectCommand="SELECT [PRID], [ProductID], [ProductName], [Price], [Quantity], [Amount] FROM [PRDetails] WHERE ([PRID] = #PRID)">
<SelectParameters>
<asp:QueryStringParameter Name="PRID" QueryStringField="ID" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<div class="container">
<div class="pull-right col-lg-5">
<h4 />SUB TOTAL Php <asp:Label ID="lbSubTotal" runat="server"></asp:Label>
<h4 />VAT (12%)
Php <asp:Literal ID="ltVAT" runat="server"></asp:Literal>
<h4 />TOTAL Php <asp:Literal ID="ltTotal" runat="server"> </asp:Literal>
</div>
</div>
<div class="pull-right">
<td>
<asp:Button ID="btnSum" runat="server" class="btn btn-default" style="background-color:Silver" text="TOTAL" ForeColor="Black" />
</td>
</div>
<br />
<br />
<br />
<br />
<div class="form-group">
<label class="control-label col-lg-4">Remarks</label>
<div class="col-lg-8">
<asp:TextBox ID="txtRemarks" runat="server" class="form- control" MaxLength="100" TextMode="MultiLine" />
</div>
</div>
<div class="pull-right">
<div class="form-group">
<asp:Button ID="btnApprove" runat="server" class="btn btn-success" text="Approve"
onclick="btnApprove_Click" />
<asp:Button ID="btnCancel" runat="server" class="btn" style="color:White" text="Disapprove" BackColor="Black" PostBackUrl="~/Default.aspx" />
</div>
</div>
</div>
</form>
HERE is BTN codes (APPROVE)
void addtoPO()
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "INSERT INTO PO2 VALUES (#UserID, #SupplierID, #CompanyName, #ShippingMethod, " +
"#ShippingTerm, #Term, #DeliveryDate, #ModifiedBy, #DateModified, #Status, #Remarks, #PODate, #DeliveryDate)";
cmd.Parameters.AddWithValue("#UserID", Session["userid"].ToString());
cmd.Parameters.AddWithValue("#SupplierID", lbSupplierID.Text);
cmd.Parameters.AddWithValue("#CompanyName", lbCompName.Text);
cmd.Parameters.AddWithValue("#ShippingMethod", lbShippingMethod.Text);
cmd.Parameters.AddWithValue("#ShippingTerm", lbShippingTerm.Text);
cmd.Parameters.AddWithValue("#Term", lbPaymentTerm.Text);
cmd.Parameters.AddWithValue("#ModifiedBy", lbFNA.Text + lbLNA.Text);
cmd.Parameters.AddWithValue("#DateModified", DateTime.Now);
cmd.Parameters.AddWithValue("#Status", "Approved");
cmd.Parameters.AddWithValue("#Remarks", txtRemarks.Text);
cmd.Parameters.AddWithValue("#PODate", DateTime.Now);
cmd.Parameters.AddWithValue("#DeliveryDate", txtDate.Text);
cmd.ExecuteNonQuery();
con.Close();
}
protected void btnApprove_Click(object sender, EventArgs e)
{
addtoPO();
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
int ProductID = int.Parse(GridView1.Rows[row.RowIndex].Cells[1].Text);
string ProductName = GridView1.Rows[row.RowIndex].Cells[2].Text;
decimal Price = decimal.Parse(GridView1.Rows[row.RowIndex].Cells[3].Text);
int Quantity = int.Parse(GridView1.Rows[row.RowIndex].Cells[4].Text);
int Amount = int.Parse(GridView1.Rows[row.RowIndex].Cells[5].Text);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "INSERT INTO PODetails (ProductID, Name, Price, Quantity, Amount) " +
"VALUES (#ProductID, #Name, #Price, #Quantity, #Amount)";
//cmd.Parameters.AddWithValue("#UserID", Session["userid"].ToString());
cmd.Parameters.Add("#ProductID", SqlDbType.VarChar).Value = ProductID;
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = ProductName.ToString();
cmd.Parameters.Add("#Price", SqlDbType.Decimal).Value = Price;
cmd.Parameters.Add("#Quantity", SqlDbType.Int).Value = Quantity;
cmd.Parameters.Add("#Amount", SqlDbType.Int).Value = Amount;
cmd.ExecuteNonQuery();
GridView1.EditIndex = -1;
GridView1.DataBind();
//con.Open();
//cmd.CommandText = "DELETE FROM Orders";
//cmd.Parameters.Add("#RefNo", RefNo);
con.Close();
}
}
I am INSERTING INTO TWO different tables that's why insert are separated and other values are being GET into GRIDVIEW.
I Have turning on and off the is identity but didn't work.
Other insert that i have are all good this was just the one has error.

insert into TABLE ([column list])
values ([values list])
you have not listed inserted column list thus server tries to fulfill all the columns "left to right". next error would be about not enough values provided for table columns. Currently it tries to post #UserID into PO2.ID, #SupplierID into PO2.UserID and so on.

Thank you for answering guys really appreciate it!
Forgive my questions because i am super new to hard codes c# and asp.net
i just followed the answer of mr #Ivan Starostin
cmd.CommandText = "INSERT INTO PO2 (UserID, SupplierID, CompanyName, ShippingMethod, " +
"ShippingTerm, Term, ModifiedBy, DateModified, Status, Remarks, PODate, DeliveryDate, FinalDeliveryDate, PRID) VALUES (#UserID, #SupplierID, #CompanyName, #ShippingMethod, " +
"#ShippingTerm, #Term, #ModifiedBy, #DateModified, #Status, #Remarks, #PODate, #DeliveryDate, #FinalDeliveryDate, #PRID)";
did it like this and fixed some column insert statement and worked!

Related

Textbox with textmode time, won't display data from sql database

So i did a research about textmode time but it doesn't seem to help me. My problem is when i tried to bind the data with time textmode it won't display anything I already tried removing the textmode so i can see if it can display data and it does. Here's my code in the front, hope you'll help me. Thank you in advance
<asp:Repeater runat="server" ID="rptrTRFFormItems" OnItemDataBound="rptrTRFFormItems_ItemDataBound">
<ItemTemplate>
<tr>
<td>
<asp:Label runat="server" ID="No" Text='<%# Container.ItemIndex + 1 %>' Visible="false">
</asp:Label>
</td>
<td>
<asp:LinkButton runat="server" ID="btnAddItemRow" CssClass="actionbtnstyle fa fa-plus-square" CausesValidation="false" OnClick="btnAddItemRows" Style="font-size: 20px;">
</asp:LinkButton>
</td>
<td>
<asp:LinkButton runat="server" ID="btnDeleteItemRow" CssClass="actionbtnstyle fa fa-minus-square" CausesValidation="false" OnClick="btnDeleteItemRows" Style="font-size: 20px;">
</asp:LinkButton>
</td>
<td>
<div runat="server" id="divInputGroup">
<span runat="server" id="spanInputGroup">
<asp:Label runat="server" ID="validatetbName">
</asp:Label>
</span>
<asp:TextBox runat="server" ID="tbName" Text='<%#Eval("Name") %>' CssClass="form-control rptrtbstyle" ondrop="return false" title="Required" data-toggle="tooltip" TabIndex="13" data-placement="bottom">
</asp:TextBox>
</div>
</td>
<td>
<asp:UpdatePanel runat="server" ID="rptriddate" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="tbDate" EventName="TextChanged" />
</Triggers>
<ContentTemplate>
<div runat="server" id="divInputGroup0">
<span runat="server" id="spanInputGroup0">
<asp:Label runat="server" ID="validatetbDate">
</asp:Label>
</span>
<asp:TextBox runat="server" ID="tbDate" CssClass="form-control js-datepicker rptrtbstyle" Style="cursor: pointer;" TabIndex="14" data-toggle="tooltip" data-placement="bottom" title="Required" OnTextChanged="tbDate_TextChanged" autocomplete="off" AutoPostBack="true">
</asp:TextBox>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</td>
<td>
<div runat="server" id="divInputGroup2">
<span runat="server" id="spanInputGroup2">
<asp:Label runat="server" ID="validatetbPreferredTime">
</asp:Label>
</span>
<asp:TextBox runat="server" ID="tbPreferredTime" Text='<%#Eval("PreferredTime") %>' format="HH:mm" TextMode="Time" CssClass="form-control rptrtbstyle" data-toggle="tooltip" TabIndex="15" data-placement="bottom" title="Required">
</asp:TextBox>
</div>
</td>
<td>
<div runat="server" id="divInputGroup1">
<span runat="server" id="spanInputGroup1">
<asp:Label runat="server" ID="validatetbFromRptr">
</asp:Label>
</span>
<asp:TextBox runat="server" ID="tbFromRptr" Text='<%#Eval("FromRptr") %>' CssClass="form-control rptrtbstyle" data-toggle="tooltip" data-placement="bottom" TabIndex="16" title="Required" AutoPostBack="false">
</asp:TextBox>
</div>
</td>
<td>
<asp:LinkButton runat="server" ID="btnExchange" CssClass="actionbtnstyle fa fa-exchange" CausesValidation="false" Style="font-size: 20px;">
</asp:LinkButton>
</td>
<td>
<div runat="server" id="divInputGroup3">
<span runat="server" id="spanInputGroup3">
<asp:Label runat="server" ID="validatetbToRptr">
</asp:Label>
</span>
<asp:TextBox runat="server" ID="tbToRptr" Text='<%#Eval("ToRptr") %>' CssClass="form-control rptrtbstyle" TabIndex="17" data-toggle="tooltip" data-placement="bottom" title="Required">
</asp:TextBox>
</div>
</td>
</tr>
<%--</ContentTemplate> </asp:UpdatePanel>--%>
</ItemTemplate>
</asp:Repeater>
And here's the code to bind data from behind.
using(SqlConnection con = new SqlConnection(travelrequest))
{
using(SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "TRFSearchByRefernce";
cmd.Parameters.AddWithValue("#trfNo", txtSearchByReference.Text);
cmd.Parameters.AddWithValue("#fullname", lblFullname01.Text);
using(SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
adp.Fill(dt);
if(dt.Rows.Count > 0)
{
rptrTRFFormItems.DataSource = dt;
rptrTRFFormItems.DataBind();
ViewState["CurrentTable"] = dt;
}
else
{
SetInitialRow();
}
}
}
}
and here's my stored procedure sql query
SELECT
[TRFGName] as Name
,[TRFGDate] as [Date]
,[TRFGTimeRef] as PreferredTime
,[TRFGFrom] as FromRptr
,[TRFGTo] as ToRptr
,[TRFGNo]
,[TRFGControlNo]
,[TRFRequester]
FROM [TRAVELREQUESTFORM].[TRAVEL].[TRAVELGRID] WHERE TRFGControlNo = #trfNo and TRFRequester = #fullname

radio button in gridview template field

I am making a exam web application in ASP.NET. I am using grid-view for showing question and the possible answers. I set size of grid view is 1 so it display only one question on a page-index. I am using radio button for multiple choice option.
When I select a radio button and going to next question or next page index of grid-view and come again previous question then I see that the radio button which I selected previously is not selected. What should I do for this?
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AutoGenerateColumns="False" DataKeyNames="id" DataSourceID="SqlDataSource1"
GridLines="None" Height="380px"
onpageindexchanging="GridView1_PageIndexChanging"
onprerender="GridView1_PreRender" onrowcommand="GridView1_RowCommand"
OnRowDataBound="GridView1_RowDataBound"
onselectedindexchanged="GridView1_SelectedIndexChanged" PageSize="1"
ShowHeader="False" style="margin-right: 0px; margin-bottom: 0px;"
Width="100%">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<table style=" width:100%; height: 550px;">
<tr>
<td class="style6" colspan="2" colspan="3"
style="border-width: 1px; border-bottom-style: inset;">
<asp:Label ID="Label14" runat="server" Font-Size="Large" Text="Question No :-"></asp:Label>
<asp:Label ID="Label4" runat="server" Font-Bold="True" Font-Size="Large"
Text='<%# Eval("id") %>'></asp:Label>
</td>
</tr>
<tr>
<td class="style4" colspan="2" colspan="2">
<asp:Label ID="Label15" runat="server" Font-Bold="True" Text="Question:-"
Font-Size="Large"></asp:Label>
<br /> <asp:Label ID="Label6" runat="server" Font-Bold="False"
Text='<%# Eval("Question") %>'></asp:Label>
</td>
</tr>
<tr>
<td class="style9" style=" padding-top:10px">
A:-<asp:RadioButton ID="RadioButton1" runat="server" AutoPostBack="True"
Font-Bold="False"
oncheckedchanged="RadioButton1_CheckedChanged" Text='<%# Eval("A") %>' />
<br />
</td>
<td class="style1" rowspan="4" style=" padding-top:10px">
<asp:Image ID="Image1" runat="server" BorderStyle="None" Height="149px"
ImageUrl='<%# Eval("image") %>' Width="449px" />
</td>
</tr>
<tr>
<td class="style9">
B:-<asp:RadioButton ID="RadioButton2" runat="server" AutoPostBack="True"
Font-Bold="False"
oncheckedchanged="RadioButton2_CheckedChanged" Text='<%# Eval("B") %>' />
<br />
</td>
</tr>
<tr>
<td class="style9">
C:-<asp:RadioButton ID="RadioButton3" runat="server" AutoPostBack="True"
Font-Bold="False"
oncheckedchanged="RadioButton3_CheckedChanged" Text='<%# Eval("C") %>' />
<br />
</td>
</tr>
<tr>
<td class="style9">
D:-<asp:RadioButton ID="RadioButton4" runat="server" AutoPostBack="True"
Font-Bold="False"
oncheckedchanged="RadioButton4_CheckedChanged" Text='<%# Eval("D") %>' />
<br />
</td>
</tr>
<tr>
<td colspan="2">
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<asp:Button ID="Button12" runat="server" BackColor="#006699" BorderStyle="None"
Font-Bold="True" Font-Size="Large" ForeColor="White" Height="34px"
Text="Next>>>" Width="230px" />
<asp:Button ID="Button2" runat="server" BackColor="#006699" BorderStyle="None"
CommandArgument='<%# Eval("id") %>' CommandName="Next" Font-Bold="True"
Font-Size="Large" ForeColor="White" Height="34px" Text="Mark for Review & Next"
Width="229px" />
<asp:Button ID="Button1" runat="server" BackColor="#006699" BorderStyle="None"
CommandArgument='<%# Eval("id") %>' CommandName="Save" Font-Bold="True"
Font-Size="Large" ForeColor="White" Height="34px" OnClick="Button1_Click"
Text="Save and Next" Width="230px" />
</td>
</tr>
</table>
</ItemTemplate>
<AlternatingItemTemplate>
<table style=" width:100%; height: 550px;">
<tr>
<td class="style9" colspan="2">
Q<span ID="GridView1_ctl02_Label14" style="font-size:Large;">0</span> .
<span ID="GridView1_ctl02_Label6" style="font-size:Large;font-weight:bold;">abc</span>
</td>
</tr>
<tr>
<td class="style9">
C:-<span style="font-size:Large;font-weight:normal;"><input
ID="GridView1_ctl02_RadioButton3" name="GridView1$ctl02$RadioButton3"
onclick="javascript:setTimeout('__doPostBack(\'GridView1$ctl02$RadioButton3\',\'\')', 0)"
type="radio" value="RadioButton3" /><label
for="GridView1_ctl02_RadioButton3">abc</label></span>
<br />
</td>
<td class="style6" colspan="2"
style=" border-width: 1px; border-bottom-style: inset;">
A:-<span style="font-size:Large;font-weight:bold;"
ID="GridView1_ctl02_Label4"><input
ID="GridView1_ctl02_RadioButton1" name="GridView1$ctl02$RadioButton1"
onclick="javascript:setTimeout('__doPostBack(\'GridView1$ctl02$RadioButton1\',\'\')', 0)"
type="radio" value="RadioButton1" /><label
for="GridView1_ctl02_RadioButton1">abc</label></span>
<br />
</td>
<td class="style1" rowspan="4" style=" padding-top:10px">
<img ID="GridView1_ctl02_Image1" Src=""
style="border-style:None;height:98px;width:231px;border-width:0px;" />
</td>
</tr>
<tr>
<td class="style4" colspan="2">
B:-<span style="font-weight:bold;" ID="GridView1_ctl02_Label15"><input
ID="GridView1_ctl02_RadioButton2" name="GridView1$ctl02$RadioButton2"
onclick="javascript:setTimeout('__doPostBack(\'GridView1$ctl02$RadioButton2\',\'\')', 0)"
type="radio" value="RadioButton2" /><label
for="GridView1_ctl02_RadioButton2">abc</label></span>
<br />
</td>
</tr>
<tr>
</tr>
<tr>
<td class="style9">
D:-<span style="font-size:Large;font-weight:normal;"><input
ID="GridView1_ctl02_RadioButton3" name="GridView1$ctl02$RadioButton3"
onclick="javascript:setTimeout('__doPostBack(\'GridView1$ctl02$RadioButton3\',\'\')', 0)"
type="radio" value="RadioButton3" /><label
for="GridView1_ctl02_RadioButton4">abc</label></span>
<br />
</td>
</tr>
<tr>
<td colspan="2">
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<input ID="GridView1_ctl02_Button12" name="GridView1$ctl02$Button12"
style="color:White;background-color:#006699;border-style:None;font-size:Large;font-weight:bold;height:34px;width:230px;"
type="submit" value="<<<Prv" /> <input
ID="GridView1_ctl02_Button2" name="GridView1$ctl02$Button2"
style="color:White;background-color:#006699;border-style:None;font-size:Large;font-weight:bold;height:34px;width:229px;"
type="submit" value="Mark and Next" />
<input ID="GridView1_ctl02_Button1" name="GridView1$ctl02$Button1"
style="color:White;background-color:#006699;border-style:None;font-size:Large;font-weight:bold;height:34px;width:230px;"
type="submit" value="Save and Next" />
</td>
</tr>
</table>
</AlternatingItemTemplate>
</asp:TemplateField>
</Columns>
<PagerStyle BackColor="White" BorderColor="White" ForeColor="White" />
</asp:GridView>
Save Answer in View-state using code
if (e.CommandName == "Save")
{
foreach (GridViewRow row in GridView1.Rows)
{
if (((RadioButton)row.FindControl("RadioButton1")).Checked)
{
Label12.Text = "A";
}
if (((RadioButton)row.FindControl("RadioButton2")).Checked)
{
Label12.Text = "B";
}
if (((RadioButton)row.FindControl("RadioButton3")).Checked)
{
Label12.Text = "C";
}
if (((RadioButton)row.FindControl("RadioButton4")).Checked)
{
Label12.Text = "D";
}
string m = Convert.ToString(e.CommandArgument);
ViewState[m] = Label12.Text;
}
Run a for Loop in Row Data Bound event of GridView1
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string id = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "id"));
int i, j;
for (i = 1; i <= 65; i++)
{
j = i + 100;
string k = i.ToString();
string l = j.ToString();
if (ViewState[l] != null)
{
if (id == k)
{
if (ViewState[l].ToString() == "A")
{
(e.Row.Cells[0].FindControl("RadioButton1") as RadioButton).Checked = true;
}
if (ViewState[l].ToString() == "B")
{
(e.Row.Cells[0].FindControl("RadioButton2") as RadioButton).Checked = true;
}
if (ViewState[l].ToString() == "C")
{
(e.Row.Cells[0].FindControl("RadioButton3") as RadioButton).Checked = true;
}
if (ViewState[l].ToString() == "D")
{
(e.Row.Cells[0].FindControl("RadioButton4") as RadioButton).Checked = true;
}
}
}
}
}
}
Solve !!!!!

How to stop loading the whole HTML page in registration form ? - ASP.NET

I'm working with ASP.NET web application . i have done a registration form but whenever the user type the Username or Email it will loads whole first_home page ! how i can stop loading the whole page ? i have setup a constraint in the database for the Username and Email to avoid the duplication.
the HTML code:
<table align="left" class="auto-style8" dir="rtl">
<tr>
<td class="auto-style13">username </td>
<td class="auto-style10">
<br />
<asp:TextBox ID="TextBoxUsername" runat="server" AutoPostBack="true" Height="25px" Width="223px" ForeColor="#990033" OnTextChanged="TextBoxUsername_TextChanged"></asp:TextBox>
<br />
</td>
<td class="auto-style11">
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="TextBoxUsername" ErrorMessage="write username"></asp:RequiredFieldValidator>
</td>
<td>
</td>
</tr>
<tr>
<td class="auto-style13">password</td>
<td class="auto-style10">
<br />
<asp:TextBox ID="TextBoxPassword" runat="server" Height="25px" Width="223px" ForeColor="#990033" TextMode="Password" OnTextChanged="TextBoxPassword_TextChanged"></asp:TextBox>
<br />
</td>
<td class="auto-style11">
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="TextBoxPassword" ErrorMessage="must write the password"></asp:RequiredFieldValidator>
</td>
<td>
</td>
</tr>
<tr>
<td class="auto-style13">confirm password </td>
<td class="auto-style10">
<br />
<asp:TextBox ID="TextBoxCPassword" runat="server" Height="25px" Width="223px" ForeColor="#990033" TextMode="Password" OnTextChanged="TextBoxCPassword_TextChanged"></asp:TextBox>
<br />
</td>
<td class="auto-style11">
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="TextBoxCPassword" ErrorMessage="must write the password"></asp:RequiredFieldValidator>
<br />
<asp:CompareValidator ID="CompareValidator1" runat="server" ControlToCompare="TextBoxPassword" ControlToValidate="TextBoxCPassword" ErrorMessage="wrong password"></asp:CompareValidator>
</td>
<td>
</td>
</tr>
<tr>
<td class="auto-style13">email</td>
<td class="auto-style10">
<br />
<asp:TextBox ID="TextBoxEmail" runat="server" AutoPostBack="true" Height="25px" Width="223px" ForeColor="#990033" TextMode="Email" OnTextChanged="TextBoxEmail_TextChanged"></asp:TextBox>
<br />
</td>
<td class="auto-style11">
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="TextBoxEmail" ErrorMessage="must write email"></asp:RequiredFieldValidator>
<br />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="TextBoxEmail" ErrorMessage="the email no valid" ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
</td>
<td>
</td>
</tr>
<tr>
<td class="auto-style13"> </td>
<td class="auto-style10">
<asp:Button ID="Button6" runat="server" OnClick="Button6_Click" Text="done" ForeColor="#990033" />
</td>
<td class="auto-style11"> </td>
<td> </td>
</tr>
</table>
the first_home.aspx.cs code:
public partial class First_home : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString);
conn.Open();
// check if the username is taken before
string checkuser = "Select count(*) from Users where Username='" + TextBoxUsername.Text + "'";
SqlCommand com = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
if (temp == 1)
{ Response.Write("error"); }
conn.Close();
}
}
protected void Button6_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString);
conn.Open();
string insertQuery = "insert into Users (Username,Password,Email) values (#username, #password, #email)";
SqlCommand com = new SqlCommand(insertQuery, conn);
com.Parameters.AddWithValue("#username", TextBoxUsername.Text);
com.Parameters.AddWithValue("#password", TextBoxPassword.Text);
com.Parameters.AddWithValue("#email", TextBoxEmail.Text);
com.ExecuteNonQuery();
conn.Close();
Response.Redirect("Seller_Registration.aspx");
}
catch (Exception ex)
{ Response.Write("error "); }
}
also the database CONSTRAINT :
CONSTRAINT [AK_Users_Email] UNIQUE NONCLUSTERED ([Email] ASC),
CONSTRAINT [AK_Users_Username] UNIQUE NONCLUSTERED ([Username] ASC),
Remove the AutoPostBack="true" attribute from those two controls.
Those two controls are causing PostBack whenever you are typing something and focusing out of that control. That is the reason behind the whole page load.

Login error in asp.net

Login error in asp.net like the name UserName does not exist in the current context and The name Password does not exist in the current context.
Asp.code
<asp:Login ID="Login1" runat="server" BackColor="#F7F7DE" BorderColor="#CCCC99" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" Font-Size="10pt" Height="242px" Width="448px">
<LayoutTemplate>
<table cellpadding="1" cellspacing="0" style="border-collapse:collapse;">
<tr>
<td>
<table cellpadding="0" style="height:242px;width:448px;">
<tr>
<td align="center" colspan="2" style="color:White;background-color:#6B696B;font-weight:bold;">Log In</td>
</tr>
<tr>
<td align="right">
<asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">Username:</asp:Label>
</td>
<td>
<asp:TextBox ID="UserName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName" ErrorMessage="User Name is required." ToolTip="User Name is required." ValidationGroup="Login1">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="right">
<asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label>
</td>
<td>
<asp:TextBox ID="Password" runat="server" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="PasswordRequired" runat="server" ControlToValidate="Password" ErrorMessage="Password is required." ToolTip="Password is required." ValidationGroup="Login1">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<asp:CheckBox ID="RememberMe" runat="server" Text="Remember me next time." />
</td>
</tr>
<tr>
<td align="center" colspan="2">
<asp:Button ID="LoginButton" runat="server" CommandName="Login" Text="Log In" ValidationGroup="Login1" OnClick="LoginButton_Click" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</LayoutTemplate>
<TitleTextStyle BackColor="#6B696B" Font-Bold="True" ForeColor="#FFFFFF" />
</asp:Login>
C# code
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Project_DBConnectionString"].ConnectionString)
SqlCommand cmd = new SqlCommand("select * from signin where Username =#username and Password=#password", con);
cmd.Parameters.AddWithValue("#username", UserName.Text);
cmd.Parameters.AddWithValue("#password", Password.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Response.Redirect("Default.aspx");
}
else
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Invalid Username and Password')</script>");
}
On the login control you need to use the FindControl to get this two TextBox and they are not direct available to the page.
So use this to get access to them
TextBox TheUserName = Login1.FindControl("UserName") as TextBox;
TextBox ThePassword = Login1.FindControl("Password") as TextBox;
and then use them on your code
cmd.Parameters.AddWithValue("#username", TheUserName.Text);
cmd.Parameters.AddWithValue("#password", ThePassword.Text);

Update query not firing properly. Update does not reflect

My Code Behind File is UpdatePublication.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;
namespace SBAIMS
{
public partial class UpdatePublisher : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["P_Id"] != null)
{
string s = Request.QueryString["P_Id"].ToString();
SqlConnection con = new SqlConnection(#"Data Source=AP\sqlexpress;Initial Catalog=SBAIMS;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select * from Publication_Master where P_Id='" + s + "' ", con);
SqlDataAdapter adptr = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adptr.Fill(ds, "Publication_Master");
if (ds.Tables["Publication_Master"].Rows.Count > 0)
{
upub.Text = ds.Tables["Publication_Master"].Rows[0]["Publication"].ToString();
upname.Text = ds.Tables["Publication_Master"].Rows[0]["Publisher"].ToString();
upc1.Text = ds.Tables["Publication_Master"].Rows[0]["P_Contact"].ToString();
upc2.Text = ds.Tables["Publication_Master"].Rows[0]["P_Contact2"].ToString();
upemail.Text = ds.Tables["Publication_Master"].Rows[0]["P_Email"].ToString();
upban.Text = ds.Tables["Publication_Master"].Rows[0]["P_BankAccount"].ToString();
}
con.Close();
}
}
protected void submitupdatepub_Click(object sender, EventArgs e)
{
string s = Request.QueryString["P_Id"].ToString();
SqlConnection con2 = new SqlConnection(#"Data Source=AP\sqlexpress;Initial Catalog=SBAIMS;Integrated Security=True");
con2.Open();
SqlCommand cmd2 = new SqlCommand("UPDATE Publication_Master SET Publication='" + upub.Text + "', Publisher='" + upname.Text + "', P_Contact='" + upc1.Text + "', P_Contact2='" + upc2.Text + "', P_Email='" + upemail.Text + "', P_BankAccount='" + upban.Text + "' WHERE P_Id='"+s+"'", con2);
cmd2.ExecuteNonQuery();
con2.Close();
Response.Redirect("~/UPublisher.aspx");
}
}
}
My ASPX file is UpdatePublication.aspx
<%# Page Title="Update Publication" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
CodeBehind="UpdatePublication.aspx.cs" Inherits="SBAIMS.UpdatePublisher" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div id="updatepublisher">
<table width="100%" class="table table-borderless table-responsive">
<tr>
<td width="50%" style="vertical-align: top;">
<div class="panel panel-success" id="updatepub">
<div class="panel-heading">
<h4>
<b>Update Publication.</b></h4>
</div>
<div class="panel-body">
<h5>
Update data about Publication.</h5>
<br />
<div align="center">
<asp:Label ID="updatepubsubmit" runat="server" Font-Size="Medium" Text="Update Was Successful !!"
CssClass="alert alert-success alcntr" Visible="False"></asp:Label>
</div>
<br />
<br />
<table class="table table-borderless table-responsive fs15" align="center" style="width: 500px; background-color: transparent;">
<tr>
<td width="40%">
Publication Name
</td>
<td width="60%">
<asp:TextBox ID="upub" CssClass="form-control fs15" autocomplete="off" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator8" runat="server" ErrorMessage="* Field Required"
ControlToValidate="upub" Display="Dynamic" SetFocusOnError="True" Font-Size="Medium"
CssClass="rfvlabel" ValidationGroup="rfvup"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
Publisher (/Distributor) Name
</td>
<td>
<asp:TextBox ID="upname" CssClass="form-control fs15" autocomplete="off" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator9" runat="server" ErrorMessage="* Field Required"
ControlToValidate="upname" Display="Dynamic" SetFocusOnError="True" Font-Size="Medium"
CssClass="rfvlabel" ValidationGroup="rfvup"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator9" runat="server" ErrorMessage="* Enter characters or valid symbols" ControlToValidate="upname" Display="Dynamic" SetFocusOnError="True" Font-Size="Medium"
CssClass="rfvlabel" ValidationExpression="^[a-zA-Z''-'\s]{1,40}$" ValidationGroup="rfvup"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
Contact No. 1
</td>
<td>
<asp:TextBox ID="upc1" CssClass="form-control fs15" autocomplete="off" placeholder="optional" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator10" runat="server" ErrorMessage="* Numbers Only"
ControlToValidate="upc1" Display="Dynamic" SetFocusOnError="True" Font-Size="Medium"
CssClass="rfvlabel" ValidationExpression="^([0-9]*)$" ValidationGroup="rfvup"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
Contact No. 2
</td>
<td>
<asp:TextBox ID="upc2" CssClass="form-control fs15" autocomplete="off" placeholder="optional" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator11" runat="server" ErrorMessage="* Numbers Only"
ControlToValidate="upc2" Display="Dynamic" SetFocusOnError="True" Font-Size="Medium"
CssClass="rfvlabel" ValidationExpression="^([0-9]*)$" ValidationGroup="rfvup"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
Publisher Bank A/C No.
</td>
<td>
<asp:TextBox ID="upban" CssClass="form-control fs15" autocomplete="off" placeholder="optional" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator12" runat="server" ErrorMessage="* Numbers Only"
ControlToValidate="upban" Display="Dynamic" SetFocusOnError="True" Font-Size="Medium"
CssClass="rfvlabel" ValidationExpression="^([0-9]*)$" ValidationGroup="rfvup"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
Pub. Email ID
</td>
<td>
<asp:TextBox ID="upemail" CssClass="form-control fs15" autocomplete="off" placeholder="optional" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator13" runat="server" ErrorMessage="* Please Enter Valid Email ID"
Display="Dynamic" CssClass="rfvlabel" ControlToValidate="upemail" ValidationGroup="rfvup"
ValidationExpression="^([0-9a-zZ-Z]([-.\w]*[0-9a-zA-Z])*#([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$"></asp:RegularExpressionValidator>
</td>
</tr>
</table>
<br />
<table class="table table-borderless table-responsive" align="center" style="width: 300px;
background-color: transparent;">
<tr>
<td colspan="2" align="center">
<asp:Button ID="submitupdatepublisher" runat="server" OnClick="submitupdatepub_Click" class="btn btn-success btn-block"
Font-Size="Large" Text="Update" ValidationGroup="rfvup" />
</td>
</tr>
</table>
</div>
</div>
</td>
<td></td>
</tr>
</table>
</div>
</asp:Content>
The update doesn't work successfully. I mean it does not reflect in database. It just according to code, redirects to the specified page. Please help me where i am going wrong.
Actually the problem is now solved. I thank all of you for your concerns.
The problem was solved by just putting if not postback condition.
if (!Page.IsPostBack)
{
if (Request.QueryString["P_Id"] != null)
{
....
}
}

Categories

Resources