I'm trying to insert into a table using a stored procedure. The executed stored produce results in zero (0). I guess which means the stored procedure is successful.
But when I look at the table, the record is not added. How can I fix it?
SQL
ALTER PROCEDURE displayToDO
#ID int =2,
#Title varchar(50),
#Description varchar(255),
#Date date,
#Time time,
#Location varchar(50),
#Priority varchar(20),
#NotificationType varchar(30)
AS
BEGIN
INSERT INTO toDOLIST(ID, Title, Description, Date, Time, Location, Priority, NotificationTYPE)
VALUES (#Title, #Description, #Date, #Time, #Location, #Priority, #NotificationType)
END
Asp.net:
<form id="form1" runat="server">
<div>
<div class="insertData">
<asp:Label ID="title" runat="server" Text="Title"></asp:Label>
<asp:TextBox ID="titleBox" runat="server"></asp:TextBox><br />
<asp:Label ID="description" runat="server" Text="Description"></asp:Label>
<asp:TextBox ID="descriptionBox" runat="server"></asp:TextBox><br />
<asp:Label ID="dateLabel" runat="server" Text="Date"></asp:Label>
<asp:Calendar ID="date" runat="server"></asp:Calendar><br />
<asp:Label ID="time" runat="server" Text="Time"></asp:Label>
<asp:TextBox ID="timeBoxHr" runat="server"></asp:TextBox> <asp:TextBox ID="timeBoxMin" runat="server"></asp:TextBox>
<br />
<asp:Label ID="location" runat="server" Text="Location"></asp:Label>
<asp:TextBox ID="locationBox" runat="server"></asp:TextBox><br />
<asp:Label ID="priority" runat="server" Text="Priority"></asp:Label>
<asp:DropDownList ID="priorityDrop" runat="server">
<asp:ListItem>-</asp:ListItem>
<asp:ListItem>Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
</asp:DropDownList>
<br />
<asp:Label ID="notification" runat="server" Text="Notification Type"></asp:Label>
<asp:DropDownList ID="notificationDrop" runat="server">
<asp:ListItem>12 hrs before</asp:ListItem>
<asp:ListItem>1 day Before</asp:ListItem>
<asp:ListItem>3 Day before</asp:ListItem>
<asp:ListItem>A Week before</asp:ListItem>
</asp:DropDownList>
</div>
<br />
<asp:Button ID="Button2" runat="server" Text="Insert" onclick="Button2_Click" />
<br /><br /><br /><br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Display" />
<br /><br /><br /><br />
<asp:GridView ID="GridView1" runat="server"
onselectedindexchanged="GridView1_SelectedIndexChanged">
</asp:GridView>
</div>
</form>
C#:
protected void Button2_Click(object sender, EventArgs e)
{
String time = timeBoxHr.Text + ":" + timeBoxMin.Text + ":00";
using (SqlConnection conn = new SqlConnection(ConfigurationString))
{
SqlCommand scommand = new SqlCommand(sql, conn);
scommand.CommandType = CommandType.StoredProcedure;
scommand.Parameters.Add("#ID", SqlDbType.Int).Value = titleBox.Text;
scommand.Parameters.Add("#Title", SqlDbType.VarChar, 50).Value = titleBox.Text;
scommand.Parameters.Add("#Description", SqlDbType.VarChar, 255).Value = descriptionBox.Text;
scommand.Parameters.Add("#Date", SqlDbType.Date).Value = date.SelectedDate.ToShortDateString();
scommand.Parameters.Add("#Time", SqlDbType.Time).Value = time;
scommand.Parameters.Add("#Location", SqlDbType.VarChar, 50).Value = locationBox.Text;
scommand.Parameters.Add("#Priority", SqlDbType.VarChar, 20).Value = priorityDrop.Text;
scommand.Parameters.Add("#NotificationType", SqlDbType.VarChar, 30).Value = notificationDrop.Text;
try
{
if (scommand.Connection.State == ConnectionState.Closed)
{
scommand.Connection.Open();
}
scommand.ExecuteNonQuery();
}
catch (Exception)
{
}
finally
{
scommand.Connection.Close();
}
}
Related
I am trying to check if the email already exists in the database or not but somehow the event doesn't seem to fire at all
I want that when someone enters email id in the textbox and when it goes out focus the servervalidate event should trigger and validate the email entered
Aspx Code (customvalidator id="cv3")
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<div class="bs-container">
<div class="form-inline required">
<label class="control-label">Name:</label>
<asp:TextBox ID="name" TextMode="SingleLine" CssClass="form-control" placeholder="e.g. John Doe" required="true" runat="server" autofocus="true" CausesValidation="true"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfv1" runat="server" ControlToValidate="vendor_cpass" ValidationGroup="vg1" Display="Dynamic" ForeColor="red" Font-Names="verdana" Font-Size="10pt" ErrorMessage="Required" SetFocusOnError="true"></asp:RequiredFieldValidator>
</div>
<div class="form-inline required">
<label class="control-label">Email:</label>
<asp:TextBox ID="vendor_email" TextMode="Email" CssClass="form-control" CausesValidation="true" placeholder="e.g. me#mymail.com" required="true" runat="server"></asp:TextBox>
<asp:CustomValidator ID="cv3" runat="server" ControlToValidate="vendor_email" Display="Dynamic" Enabled="true" ErrorMessage="Already Exists" ValidationGroup="vg2" OnServerValidate="cv3_ServerValidate"></asp:CustomValidator>
<asp:RequiredFieldValidator ID="rfv2" runat="server" ControlToValidate="vendor_email" Display="Dynamic" ForeColor="red" Font-Names="verdana" Font-Size="10pt" ValidationGroup="vg2" ErrorMessage="Required" SetFocusOnError="true"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="rev1" runat="server" ControlToValidate="vendor_email" ForeColor="Red" Font-Names="verdana" Font-Size="10pt" ValidationGroup="vg2" ValidationExpression="^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$" Display = "Dynamic" ErrorMessage = "Invalid email address" SetFocusOnError="true"/>
</div>
<div class="form-inline required">
<label class="control-label">Password:</label>
<asp:TextBox ID="vendor_pass" TextMode="Password" CssClass="form-control" placeholder="Password" CausesValidation="true" required="true" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfv3" runat="server" ValidationGroup="vg3" ControlToValidate="vendor_pass" Display="Dynamic" ForeColor="red" Font-Names="verdana" Font-Size="10pt" ErrorMessage="Required" SetFocusOnError="true"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="rev2" runat="server" ValidationGroup="vg3" ControlToValidate="vendor_pass" ForeColor="Red" Font-Names="verdana" Font-Size="10pt" ValidationExpression="^(?=.*[A-Za-z])(?=.*\d)(?=.*[$#$!%*#?&])[A-Za-z\d$#$!%*#?&]{8,}$" Display="Dynamic" ErrorMessage="Minimum 8 characters atleast 1 Alphabet, 1 Number and 1 Special Character" SetFocusOnError="true"></asp:RegularExpressionValidator>
</div>
<div class="form-inline required">
<label class="control-label">Confirm Password:</label>
<asp:TextBox ID="vendor_cpass" TextMode="Password" CssClass="form-control" placeholder="Password" required="true" runat="server" CausesValidation="true" ></asp:TextBox>
<asp:CustomValidator ID="cv2" runat="server" ValidationGroup="vg4" ControlToValidate="vendor_cpass" ClientValidationFunction="cp_check" Display="Dynamic" ForeColor="red" Font-Names="verdana" Font-Size="10pt" ErrorMessage="" SetFocusOnError="true" EnableClientScript="true"/>
<asp:RequiredFieldValidator ID="rfv4" runat="server" ValidationGroup="vg4" ControlToValidate="vendor_cpass" Display="Dynamic" ForeColor="red" Font-Names="verdana" Font-Size="10pt" ErrorMessage="Required" SetFocusOnError="true"></asp:RequiredFieldValidator>
</div>
<div class="form-inline required">
<label class="control-label">Mobile No:</label>
<asp:TextBox ID="vendor_mobile" TextMode="Phone" CssClass="form-control" placeholder="e.g. 9999999999" required="true" runat="server" CausesValidation="true"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfv5" runat="server" ValidationGroup="vg5" ControlToValidate="vendor_mobile" Display="Dynamic" ForeColor="red" Font-Names="verdana" Font-Size="10pt" ErrorMessage="Required" SetFocusOnError="true"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="rev3" runat="server" ValidationGroup="vg5" ControlToValidate="vendor_mobile" ForeColor="Red" Font-Names="verdana" Font-Size="10pt" ValidationExpression="^\d{10}$" Display="Dynamic" ErrorMessage="Should be 10 digits" SetFocusOnError="true"></asp:RegularExpressionValidator>
</div>
<div class="form-inline required">
<label>Address</label>
<br />
<label class="control-label">Street Address:</label>
<asp:TextBox ID="street" TextMode="SingleLine" CssClass="form-control" placeholder="e.g. 7th Avenue Street" required="true" runat="server" CausesValidation="true"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfv6" runat="server" ValidationGroup="vg6" ControlToValidate="street" Display="Dynamic" ForeColor="red" Font-Names="verdana" Font-Size="10pt" ErrorMessage="Required" SetFocusOnError="true"></asp:RequiredFieldValidator>
<br />
<label class="control-label">City:</label>
<asp:TextBox ID="city" TextMode="SingleLine" CssClass="form-control" placeholder="e.g. Kolkata" required="true" runat="server" CausesValidation="true"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfv7" runat="server" ValidationGroup="vg6" ControlToValidate="city" Display="Dynamic" ForeColor="red" Font-Names="verdana" Font-Size="10pt" ErrorMessage="Required" SetFocusOnError="true"></asp:RequiredFieldValidator>
<br />
<label class="control-label">State:</label>
<asp:TextBox ID="state" TextMode="SingleLine" CssClass="form-control" placeholder="e.g. West Bengal" required="true" runat="server" CausesValidation="true"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfv8" runat="server" ValidationGroup="vg6" ControlToValidate="state" Display="Dynamic" ForeColor="red" Font-Names="verdana" Font-Size="10pt" ErrorMessage="Required" SetFocusOnError="true"></asp:RequiredFieldValidator>
<br />
<label class="control-label">Pincode:</label>
<asp:TextBox ID="pincode" TextMode="SingleLine" CssClass="form-control" placeholder="e.g. 700700" required="true" runat="server" CausesValidation="true"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfv9" runat="server" ValidationGroup="vg6" ControlToValidate="pincode" Display="Dynamic" ForeColor="red" Font-Names="verdana" Font-Size="10pt" ErrorMessage="Required" SetFocusOnError="true"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="rev4" runat="server" ValidationGroup="vg6" ControlToValidate="pincode" ForeColor="Red" Font-Names="verdana" Font-Size="10pt" ValidationExpression="^\d{6}$" Display="Dynamic" ErrorMessage="Should be 6 digits" SetFocusOnError="true"></asp:RegularExpressionValidator>
</div>
<div class="form-inline required">
<label>Criteria for email notification</label>
<br />
<label>Estimated cost of project</label>
<asp:DropDownList runat="server" ID="ecp" CssClass="form-control">
<asp:ListItem Text="--Any Amount--" Value="0" Selected="True"></asp:ListItem>
<asp:ListItem Text="1 Lakh and Above" Value="1"></asp:ListItem>
<asp:ListItem Text="5 Lakhs and Above" Value="5"></asp:ListItem>
<asp:ListItem Text="10 Lakhs and Above" Value="10"></asp:ListItem>
<asp:ListItem Text="50 Lakhs and Above" Value="50"></asp:ListItem>
<asp:ListItem Text="1 Crore and Above" Value="100"></asp:ListItem>
<asp:ListItem Text="5 Crores and Above" Value="500"></asp:ListItem>
<asp:ListItem Text="10 Crores and Above" Value="1000"></asp:ListItem>
<asp:ListItem Text="50 Crores and Above" Value="5000"></asp:ListItem>
</asp:DropDownList>
<br />
<label class="control-label">Please Select the Subjects for which Tender notices you are Interested</label>
<asp:CheckBox ID="main_check" Checked="true" Text="Notify me for all tenders" runat="server" Onclick="main_check_changed(this)" />
<br />
<label>Goods</label>
<br />
<asp:CheckBoxList ID="goods" runat="server" RepeatColumns="5" RepeatDirection="Horizontal"></asp:CheckBoxList>
<br />
<label>Services</label>
<asp:CheckBoxList ID="services" runat="server" RepeatColumns="5" RepeatDirection="Horizontal"></asp:CheckBoxList>
</div>
<div class="form-inline required">
<asp:Button ID="submit" runat="server" Text="Submit" Width="81px" OnClick="submit_Click" CausesValidation="true" />
<asp:Button ID="reset" runat="server" Text="Reset" Width="81px" OnClientClick="this.form.reset();return false;" />
</div>
</div>
C# code: (method cv3_ServerValidate)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
using System.Data;
using System.Configuration;
namespace Tender
{
public partial class vendor_reg : System.Web.UI.Page
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string v_id;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
MySqlConnection con = new MySqlConnection(constr);
con.Open();
MySqlCommand cmd = new MySqlCommand("select * from goods");
cmd.Connection = con;
MySqlDataReader sdr = cmd.ExecuteReader();
goods.DataSource = sdr;
goods.DataTextField = "title";
goods.DataValueField = "goods_id";
goods.DataBind();
for (int i = 0; i < goods.Items.Count; i++)
{
goods.Items[i].Selected = true;
goods.Items[i].Attributes.Add("onclick", "checkedchanged(this)");
}
con.Close();
con.Open();
MySqlCommand cmd1 = new MySqlCommand("select * from services");
cmd1.Connection = con;
MySqlDataReader sdr1 = cmd1.ExecuteReader();
services.DataSource = sdr1;
services.DataTextField = "title";
services.DataValueField = "service_id";
services.DataBind();
for (int i = 0; i < services.Items.Count; i++)
{
services.Items[i].Selected = true;
services.Items[i].Attributes.Add("onclick", "checkedchanged(this)");
}
}
}
public void MsgBox(String ex, Page pg, Object obj)
{
string s = "<SCRIPT language='javascript'>alert('" + ex.Replace("\r\n", "\\n").Replace("'", "") + "'); </SCRIPT>";
Type cstype = obj.GetType();
ClientScriptManager cs = pg.ClientScript;
cs.RegisterClientScriptBlock(cstype, s, s.ToString());
}
protected void cv3_ServerValidate(object source, ServerValidateEventArgs args)
{
MsgBox("! your message !", this.Page, this);
MySqlConnection con = new MySqlConnection(constr);
con.Open();
MySqlCommand cmd = new MySqlCommand("select vendor_id from vendor where vendor_email=#email;");
cmd.Parameters.AddWithValue("#email", vendor_email.Text);
cmd.Connection = con;
MySqlDataReader sdr = cmd.ExecuteReader();
if (sdr.HasRows)
{
cv3.ErrorMessage = "Email already exists in our database.Please check or try to login";
args.IsValid = false;
}
else
{
args.IsValid = true;
}
con.Close();
}
protected void submit_Click(object sender, EventArgs e)
{
MySqlConnection con = new MySqlConnection(constr);
con.Open();
MySqlCommand cmd = new MySqlCommand("Insert into vendor (vendor_email,vendor_pass,vendor_name,vendor_addr,vendor_phone,vendor_ecp) values(#email, Aes_Encrypt(#pass,#email), #name, #addr, #phone, #ecp)", con);
String addr = street.Text + ", " + city.Text + ", " + state.Text + ", " + pincode.Text;
cmd.Parameters.AddWithValue("#email", vendor_email.Text);
cmd.Parameters.AddWithValue("#pass", vendor_pass.Text);
cmd.Parameters.AddWithValue("#name", name.Text);
cmd.Parameters.AddWithValue("#addr", addr);
cmd.Parameters.AddWithValue("#phone", vendor_mobile.Text);
cmd.Parameters.AddWithValue("#ecp", ecp.SelectedValue);
cmd.ExecuteNonQuery();
cmd.Dispose();
MySqlCommand cmd1 = new MySqlCommand("select vendor_id from vendor where vendor_email=#email;");
cmd1.Parameters.AddWithValue("#email", vendor_email.Text);
cmd1.Connection = con;
MySqlDataReader sdr1 = cmd1.ExecuteReader();
if (sdr1.Read()) {
v_id = sdr1[0].ToString();
}
cmd1.Dispose();
MySqlCommand cmd2 = new MySqlCommand("insert into vendor_goods (vendor_id,goods_id) values(#v_id, #g_id)", con);
MySqlCommand cmd3 = new MySqlCommand("insert into vendor_services (vendor_id,service_id) values(#v_id, #s_id)", con);
for(int i = 0; i < goods.Items.Count; i++)
{
if (goods.Items[i].Selected == true)
{
cmd2.Parameters.Clear();
cmd2.Parameters.AddWithValue("#v_id", v_id);
cmd2.Parameters.AddWithValue("#g_id", goods.Items[i].Value);
cmd2.ExecuteNonQuery();
}
}
for (int i = 0; i < services.Items.Count; i++)
{
if (services.Items[i].Selected == true)
{
cmd3.Parameters.Clear();
cmd3.Parameters.AddWithValue("#v_id", v_id);
cmd3.Parameters.AddWithValue("#s_id", services.Items[i].Value);
cmd3.ExecuteNonQuery();
}
}
con.Close();
Response.Redirect("vendor_login.aspx");
}
}
}
Ok,
You need to change a few things here,
Add AutoPostBack="true" to your vendor_email textbox
Add OnTextChanged="vendor_email_TextChanged" to your vendor_email textbox
<asp:TextBox ID="vendor_email" TextMode="Email" CssClass="form-control"
OnTextChanged="vendor_email_TextChanged"
AutoPostBack="true" CausesValidation="true"
placeholder="e.g. me#mymail.com" required="true" runat="server"></asp:TextBox>
Implement the event handler in the code behind and call Validate() (Read this)
protected void vendor_email_TextChanged(object sender, EventArgs e)
{
Page.Validate();
}
And finally,
Change the name of your submit button to something else because it overwrites the submit() method of the form
<asp:Button ID="submit2" runat="server" Text="Submit" Width="81px" OnClick="submit_Click" CausesValidation="true" />
I am trying to insert a comment using repeater Control
my code in html
<asp:Repeater ID="repConcerns" runat="server" OnItemCommand="post" >
<ItemTemplate >
<div class="row col-md-12">
<div class="col-sm-2" style="background-color:#808080">
<asp:Image ID="Image1" runat="server" ImageUrl='<%#Eval("Pathh") %>' width="90px" Height="90px" CssClass="img-circle" title='<%#Eval("Name") %>'/> <br/><asp:LinkButton ID="LinkButton1" runat="server" Text='<%#Eval("Name") %>' CssClass="btn btn-info btn-sm" CommandName="btnMessage" CommandArgument='<%#Eval("Username") %>'></asp:LinkButton><br/>
</div>
<div class="col-sm-10" style="background-color:#808080" >
<asp:Label ID="Label1" width="100%" style="padding:7px;" runat="server" Enabled="false" Text='<%#Eval("Title") %>'> </asp:Label>
<asp:TextBox ID="txtMessage" placeholder="Empty Post" width="100%" style="padding:7px;" runat="server" Text='<%#Eval("Detail") %>' TextMode="MultiLine" Enabled="false" Height="100px"> </asp:TextBox>
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%#Eval("Sno") %>' />
<div class="bar"></div>
<asp:TextBox ID="txtcomment" runat="server" CssClass="form-control form-control-sm" placeholder="Comment / Write Openion Suggestion" TextMode="MultiLine" Height="40px"></asp:TextBox>
<asp:LinkButton ID="btn" runat="server" CssClass="btn btn-primary" CommandName="comment" CommandArgument='<%#Eval("Sno") %>' >Post</asp:LinkButton>
</div>
</div>
<div style="padding-bottom:10px;"></div>
<%--<br /> --%>
</ItemTemplate>
</asp:Repeater>
and C# code
protected void post(object source, RepeaterCommandEventArgs e)
{
if(e.CommandName== "comment")
{
a = e.CommandArgument.ToString();
SqlConnection con = new SqlConnection(strconn);
SqlCommand com = new SqlCommand();
com.CommandText = "insert into Comments(Sno,Comment,Username)values('" +a+ "','" + txtcomment.Text + "','" + username + "')";
con.Open();
}
}
I do not know how to insert into table "Comment".
I have made a "Page" in which their are wall posts. I have included an option for Comment. The comment button appears as it should with every post. But i do not know how to insert comment in table "Comment". i am trying to insert comment with corresponding "Sno" of Posts saved in HiddenField. But when i try to write Text Box id there "txtcomment.text" it gives me error. How do i insert.
I've made some amendments to you original code - note the comments:
protected void post(object source, RepeaterCommandEventArgs e)
{
if(e.CommandName== "comment")
{
//Find TextBox Control
TextBox txt = (TextBox)e.Item.FindControl("txtcomment");
var sno = e.CommandArgument.ToString();
SqlConnection con = new SqlConnection(strconn);
SqlCommand com = new SqlCommand();
com.CommandText = "INSERT INTO Comments(Sno,Comment,Username) VALUES (#SNO, #COMMENT, #USERNAME)";
com.Connection = con;
//Add Command Parameters
com.Parameters.AddWithValue("#SNO", sno);
com.Parameters.AddWithValue("#COMMENT", txt.Text);
com.Parameters.AddWithValue("#USERNAME", username);
con.Open();
//Execute Command
com.ExecuteNonQuery();
}
}
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!
Is there a way to generate labels based on how many user entry's there are in a database and print the database information to the labels on page load.
I have attempted to do this by binding the data but i found i can only do this in a grid format and i don't want a grid.
What i am trying to create overall is a survey in which the questions are stored in the database and displayed on the labels. I want someone to be able to add a question to the database and a label to be automatically generated for it displaying the question.
I am able to get my desired effect but i have added labels and written the questions on them manually. If anyone can please help or advise if it can be done it would be much appreciated. Thank you in advanced.
Here is what i have so far:
<h1> </h1>
<h1>PaaS Assured Server Test</h1>
<div class="row">
<div class="col-md-6">
<h2>
<asp:Label ID="lblmsg" runat="server"></asp:Label>
<asp:Panel ID="BugPanel1" runat="server" BorderColor="#FFFF99" BackColor="#FFFF99" Visible="False">
<asp:Label ID="Label4" runat="server" Text="You have informed us of an error." ForeColor="Black"></asp:Label>
<br /><asp:Label ID="Label3" runat="server" Text="Please advise of serverity. 1 - highest 5 - lowest:" ForeColor="Black"></asp:Label>
<asp:DropDownList ID="SeverityList1" runat="server" AutoPostBack="True">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
<asp:ListItem>5</asp:ListItem>
</asp:DropDownList>
<br /><asp:Label ID="Label5" runat="server" Text="Who shall be notified of the error:" ForeColor="Black"></asp:Label>
<asp:DropDownList ID="NotifyList1" runat="server" DataSourceID="SqlDataSource2" AutoPostBack="True">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:DefaultConnection %>" SelectCommand="SELECT [UserName] FROM [AspNetUsers]"></asp:SqlDataSource>
<br /><asp:Label ID="Label6" runat="server" Text="Would you like a copy emailed to yourself?" ForeColor="Black"></asp:Label>
<asp:RadioButtonList ID="EmailRadio1" runat="server" AutoPostBack="True" RepeatDirection="Horizontal">
<asp:ListItem Value="True" Text="Yes">Yes</asp:ListItem>
<asp:ListItem Value="True" Text="Yes">No</asp:ListItem>
</asp:RadioButtonList>
<asp:Button ID="BugButton" runat="server" Text="File Bug and Generate Report" CausesValidation="False" OnClick="BugButton_Click" />
</asp:Panel>
</h2>
<h2>Provisioning</h2>
<hr />
<asp:Panel ID="FormPanel1" runat="server" BackColor="#F4F4F4">
<asp:Panel ID="HeadPanel1" runat="server" BackColor="#E4E4E4" BorderColor="#999999" Font-Bold="True" ForeColor="#000066" Font-Underline="True">
<h3>Page View</h3>
</asp:Panel>
<asp:RequiredFieldValidator ID="Radio1Validator" runat="server" ErrorMessage="Error: Please select an option:" ControlToValidate="Radio1" SetFocusOnError="True" ForeColor="Red"></asp:RequiredFieldValidator>
<p />
<asp:Label ID="PALabel1" runat="server" Text="Does your screen look similar to the image displayed ?"></asp:Label>
<asp:ImageButton ID="ImageButton1" runat="server" Height="20px" ImageUrl="~/Image/PrintScreen/Info.jpg" OnClick="ImageButton1_Click" Width="21px" CausesValidation="False" /><br/>
<asp:RadioButtonList ID="Radio1" runat="server" AutoPostBack="True" RepeatDirection="Horizontal">
<asp:ListItem Value="True" Text="Yes">Yes</asp:ListItem>
<asp:ListItem Text="No" Value="False">No</asp:ListItem>
</asp:RadioButtonList>
<asp:Panel ID="PAPanel1" runat="server">
<asp:Label ID="Label1" runat="server" ForeColor="#000099" Text="Provide further details:"></asp:Label>
<asp:TextBox ID="PAText1" runat="server" BorderColor="Silver" CssClass="form-control"></asp:TextBox>
</asp:Panel>
<p />
<asp:RequiredFieldValidator ID="Radio2Validator" runat="server" ControlToValidate="Radio2" ErrorMessage="Error: Please select an option:" ForeColor="Red"></asp:RequiredFieldValidator>
<p />
<asp:Label ID="PALabel2" runat="server" Text="In "Server Name" is virtual pre-selected?"></asp:Label>
<asp:ImageButton ID="ImageButton4" height="20px" runat="server" Width="21px" CausesValidation="False" ImageUrl="~/Image/PrintScreen/Info.jpg" OnClick="ImageButton4_Click" />
<br/>
<asp:RadioButtonList ID="Radio2" runat="server" AutoPostBack="True" RepeatDirection="Horizontal">
<asp:ListItem Value="True" Text="Yes">Yes</asp:ListItem>
<asp:ListItem Text="No" Value="False">No</asp:ListItem>
</asp:RadioButtonList>
<asp:Panel ID="PAPanel2" runat="server">
<asp:Label ID="Label2" runat="server" Text="Provide further details:" ForeColor="#000099"></asp:Label>
<asp:TextBox ID="PAText2" runat="server" CssClass="form-control" BorderColor="Silver" ></asp:TextBox>
</asp:Panel>
<asp:Panel ID="HeadPanel2" runat="server" BackColor="#E4E4E4" BorderColor="#999999" Font-Bold="True" ForeColor="#000066" Font-Underline="True">
<h3>Form details</h3>
</asp:Panel>
<asp:Panel ID="SubHead1" runat="server" BackColor="#F3F3F3" BorderColor="#999999" Font-Bold="False" ForeColor="#003399" Font-Underline="True" Font-Italic="True" Font-Size="Smaller">
<h4>Request Details</h4>
</asp:Panel>
<asp:Panel ID="SubHead2" runat="server" BackColor="#F3F3F3" BorderColor="#999999" Font-Bold="False" ForeColor="#003399" Font-Underline="True" Font-Italic="True" Font-Size="Smaller">
<h4>Server Location</h4>
</asp:Panel>
<asp:Panel ID="SubHead3" runat="server" BackColor="#F3F3F3" BorderColor="#999999" Font-Bold="False" ForeColor="#003399" Font-Underline="True" Font-Italic="True" Font-Size="Smaller">
<h4>Product and Support Details</h4>
</asp:Panel>
<asp:Panel ID="SubHead4" runat="server" BackColor="#F3F3F3" BorderColor="#999999" Font-Bold="False" ForeColor="#003399" Font-Underline="True" Font-Italic="True" Font-Size="Smaller">
<h4>Server Configuration</h4>
</asp:Panel>
<asp:Label ID="PALabel3" runat="server" Text="What operating system are you testing?"></asp:Label>
<asp:ImageButton ID="ImageButton3" runat="server" Height="20px" ImageUrl="~/Image/PrintScreen/Info.jpg" OnClick="ImageButton1_Click" Width="21px" CausesValidation="False" /><br/>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Please select the server you are testing:" ControlToValidate="Radio3" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:RadioButtonList ID="Radio3" runat="server" AutoPostBack="True" RepeatDirection="Horizontal">
<asp:ListItem Value="Windows 2008 Server R2" Text="Windows 2008 Server R2">Windows 2008 Server R2</asp:ListItem>
<asp:ListItem Value="Windows 2012 Server R2" Text="Windows 2012 Server R2">Windows 2012 Server R2</asp:ListItem>
<asp:ListItem Value="RHEL" Text="RHEL">RHEL</asp:ListItem>
</asp:RadioButtonList>
<p /> <p />
<asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Submit"/>
<p />
</asp:Panel>
</div>
<div class="col-md-6">
<h2> </h2>
<h2>Information Viewer <asp:Image ID="LrgInfoImage" runat="server" ImageUrl="~/Image/PrintScreen/Info.jpg" Height="21px" Width="24px" />
  <asp:Button ID="Button2" runat="server" Text="View test history" BorderColor="#ECECFF" BorderStyle="Ridge" CssClass="btn" Font-Underline="True" ForeColor="#0066FF" Height="32px" OnClick="Button2_Click" Width="177px" CausesValidation="False" />
</h2> <hr />
<asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0">
<asp:View ID="View0" runat="server">
<div style="overflow-x:auto;width:600px" class="fixed">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="PAssuredId" DataSourceID="SqlDataSource1" AllowSorting="True" BorderColor="#F4F4F4" ForeColor="#000066" GridLines="Horizontal" Width="56%" HorizontalAlign="Center">
<AlternatingRowStyle BackColor="#F4F4FF" BorderColor="Black" ForeColor="#000066" />
<Columns>
<asp:BoundField DataField="PAssuredId" HeaderText="Test ID" InsertVisible="False" ReadOnly="True" SortExpression="PAssuredId" NullDisplayText="INVALID TEST" ItemStyle-BackColor="#F0F0FF" />
<asp:BoundField DataField="Date" HeaderText="Date/ Time" SortExpression="Date" />
<asp:BoundField DataField="UserName" HeaderText="User" SortExpression="UserName" NullDisplayText="INVALID TEST" />
<asp:BoundField DataField="Platform" HeaderText="Platform" SortExpression="Platform" NullDisplayText="User did not select platform" />
<asp:CheckBoxField DataField="VirtualPreselect" HeaderText="Virtual" SortExpression="VirtualPreselect" />
<asp:CheckBoxField DataField="DetsAccurate" HeaderText="Details ok?" SortExpression="DetsAccurate" />
<asp:CheckBoxField DataField="ScreenSame" HeaderText="Correct form?" SortExpression="ScreenSame" />
<asp:BoundField DataField="No1" HeaderText="Error 1" SortExpression="No1" NullDisplayText="No error found" ReadOnly="True" />
<asp:BoundField DataField="No2" HeaderText="Error 2" SortExpression="No2" NullDisplayText="No error found" />
<asp:BoundField DataField="No3" HeaderText="Error 3" SortExpression="No3" NullDisplayText="No error found" />
<asp:BoundField DataField="No4" HeaderText="Error 4" SortExpression="No4" NullDisplayText="No error found" />
<asp:BoundField DataField="No5" HeaderText="Error 5" SortExpression="No5" NullDisplayText="No error found" />
</Columns>
</asp:GridView>
</div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DefaultConnection %>" SelectCommand="SELECT PaaSAssuredServer.PAssuredId, PaaSAssuredServer.Date, AspNetUsers.UserName, PaaSAssuredServer.Platform, PaaSAssuredServer.VirtualPreselect, PaaSAssuredServer.DetsAccurate, PaaSAssuredServer.ScreenSame, PaaSAssuredServer.No1, PaaSAssuredServer.No2, PaaSAssuredServer.No3, PaaSAssuredServer.No4, PaaSAssuredServer.No5 FROM PaaSAssuredServer INNER JOIN AspNetUsers ON PaaSAssuredServer.UserId = AspNetUsers.Id ORDER BY PaaSAssuredServer.Date DESC"></asp:SqlDataSource>
</asp:View>
<asp:View ID="View1" runat="server">
<asp:Image ID="ScreenImge" runat="server" Height="600px" ImageUrl="~/Image/PrintScreen/PassTest1.jpg" Width="600px" />
</asp:View>
<asp:View ID="View2" runat="server">
<asp:Image ID="Image1" runat="server" Height="105px" ImageUrl="~/Image/PrintScreen/ServerType.jpg" Width="446px" />
</asp:View>
<asp:View ID="View3" runat="server">
<asp:Image ID="Image2" runat="server" ImageUrl="~/Image/PrintScreen/ServerType.jpg" Height="105px" Width="446px" />
</asp:View>
</asp:MultiView>
</div>
</div>
</asp:Content>
Here is the code behind :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Collections;
using System.Data;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Windows.Forms;
using Microsoft.AspNet.Identity;
namespace IRISTest
{
public partial class PaaSAssuredServer : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Radio1.SelectedValue == "False")
{
PAPanel1.Visible = true;
}
else
{
PAPanel1.Visible = false;
}
if (Radio2.SelectedValue == "False")
{
PAPanel2.Visible = true;
}
else
{
PAPanel2.Visible = false;
}
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
MultiView1.ActiveViewIndex = 1;
}
protected void Button2_Click(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex = 0;
}
protected void ImageButton4_Click(object sender, ImageClickEventArgs e)
{
MultiView1.ActiveViewIndex = 3;
}
protected void Submit(object sender, EventArgs e)
{
{
string message = "I can confirm the following:" + Environment.NewLine + "It is " + Radio1.SelectedValue + " that my screen matches that displayed in the image. " + Environment.NewLine +
"It is:" + Radio2.SelectedValue + " that my default Server Name is set to Virtual. " + Environment.NewLine +
"I have follwed the steps accurately and provided all requested information/ further details to enable further investigation" + Environment.NewLine +
"On hitting sumbit I am confirming that I have perfomed this test and the provided information is accurate to my knowledge.";
string caption = "Confirmation:";
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
MessageBoxIcon icon = MessageBoxIcon.Information;
MessageBoxDefaultButton defaultbutton = MessageBoxDefaultButton.Button2;
DialogResult result;
result = MessageBox.Show(message, caption, buttons, icon, defaultbutton);
if (result == DialogResult.Yes)
{
Int32 newProdID = 0;
var userId = User.Identity.GetUserId();
var connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO [PaaSAssuredServer] ([VirtualPreselect], [No1], [No2], [ScreenSame], [Date], [UserId], [Platform]) VALUES ( #VirtualPreselect, #No1, #No2, #ScreenSame, #Date, #UserId, #Platform);" + "SELECT CAST(scope_identity() AS int)");
//cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#ScreenSame", Radio1.SelectedItem.Value);
cmd.Parameters.AddWithValue("#VirtualPreselect", Radio2.SelectedItem.Value);
cmd.Parameters.AddWithValue("#No1", PAText1.Text);
cmd.Parameters.AddWithValue("#No2", PAText2.Text);
cmd.Parameters.AddWithValue("#Date", DateTime.Now);
cmd.Parameters.AddWithValue("#UserId", userId);
cmd.Parameters.AddWithValue("#Platform", Radio3.SelectedItem.Value);
//cmd.Parameters.AddWithValue("#UserId", 0);
//cmd.Parameters["#UserId"].Direction = ParameterDirection.InputOutput;
connection.Open();
try
{
newProdID = (Int32)cmd.ExecuteScalar();
//int UserId = (int)cmd.Parameters["#UserId"].Value;
//cmd.ExecuteNonQuery();
//var rowCount = cmd.ExecuteScalar();
lblmsg.Text = "You have completed and recorded the test Sucessfully " + Environment.NewLine +
"Your test number is: " + newProdID;
lblmsg.ForeColor = System.Drawing.Color.Green;
}
catch (SqlException sqlEx)
{
lblmsg.Text = sqlEx.Message;
lblmsg.ForeColor = System.Drawing.Color.Red;
}
finally
{
connection.Close();
}
if (PAText1.Text == "0")
{
BugPanel1.Visible = true;
}
else
{
BugPanel1.Visible = false;
}
if (PAText2.Text == "0")
{
BugPanel1.Visible = true;
}
else
{
BugPanel1.Visible = false;
}
}
}
}
}
protected void BugButton_Click(object sender, EventArgs e)
{
Int32 newProdID1 = 0;
var userId = User.Identity.GetUserId();
var BugTest = true;
var connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO [BugRep] ([Bug], [Serverity], [CorrName], [UserId]) VALUES (#Bug, #Serverity, #CorrName, #UserId);" + "SELECT CAST(scope_identity() AS int)");
//cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#Serverity", SeverityList1.SelectedItem.Value);
cmd.Parameters.AddWithValue("#CorrName", NotifyList1.SelectedItem.Value);
cmd.Parameters.AddWithValue("#Bug", BugTest);
cmd.Parameters.AddWithValue("#UserId", userId);
cmd.Parameters.AddWithValue("#Platform", Radio3.SelectedItem.Value);
//cmd.Parameters.AddWithValue("#UserId", 0);
//cmd.Parameters["#UserId"].Direction = ParameterDirection.InputOutput;
connection.Open();
try
{
newProdID1 = (Int32)cmd.ExecuteScalar();
//int UserId = (int)cmd.Parameters["#UserId"].Value;
//cmd.ExecuteNonQuery();
//var rowCount = cmd.ExecuteScalar();
lblmsg.Text = "You have reported the bug sucessfully and" + NotifyList1.SelectedItem.Value + "has been informed." + Environment.NewLine +
"Your test number is: " + newProdID1;
lblmsg.ForeColor = System.Drawing.Color.Green;
}
catch (SqlException sqlEx)
{
lblmsg.Text = sqlEx.Message;
lblmsg.ForeColor = System.Drawing.Color.Red;
}
finally
{
connection.Close();
}
}
}
}
}
You are on the right track to use data binding. If you want to have more control over the HTML that is generated, you can use a Repeater control. This way, you can specify templates for the items you want to display.
The following sample shows a Repeater. In the ItemTemplate, a HiddenField stores the question id and a Label shows the text. When the page is requested, the items are retrieved from a database (the sample uses test data) and bound to the Repeater. I've also added a dropdown in the ItemTemplate so that the user can select an answer. Upon clicking the Save button, the values are retrieved from the controls in the items of the Repeater.
ASPX
<asp:Repeater ID="rpt" runat="server">
<ItemTemplate>
<p>
<asp:HiddenField ID="hiddenId" runat="server" Value='<%# Eval("Id") %>' />
<asp:Label ID="lblQuestion" runat="server" Text='<%# Eval("Text") %>' />
<asp:DropDownList ID="ddlAnswer" runat="server">
<asp:ListItem Text="1" />
<asp:ListItem Text="2" />
<asp:ListItem Text="3" />
</asp:DropDownList>
</p>
</ItemTemplate>
</asp:Repeater>
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
Code Behind
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
var questions = GetQuestions();
rpt.DataSource = questions;
rpt.DataBind();
}
}
private IEnumerable<Question> GetQuestions()
{
// Load questions from database
// Setting up some sample data for this sample
var lst = new List<Question>();
return Enumerable.Range(1, 5).Select(x => new Question() { Id = x, Text = "Question " + x.ToString() });
}
protected void btnSave_Click(object sender, EventArgs e)
{
var dictAnswers = GetValuesFromRepeater();
// Save answers to database
}
private IDictionary<int, int> GetValuesFromRepeater()
{
var dict = new Dictionary<int, int>();
foreach (RepeaterItem item in rpt.Items)
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
var id = int.Parse(((HiddenField)item.FindControl("hiddenId")).Value);
var answer = int.Parse(((DropDownList)item.FindControl("ddlAnswer")).Text);
dict.Add(id, answer);
}
}
return dict;
}
}
public class Question
{
public int Id { get; set; }
public string Text { get; set; }
}
Please note that when retrieving the values from the repeater, the controls have to be found by their id using the FindControl method.
SqlConnection con = new SqlConnection(connectionstring);
SqlCommand cmd = new SqlCommand ("select fields from database", con);
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
foreach (DataRow dr in DataSet.Tables[0].Rows){
Label lbl = new Label();
lbl.Text = dr["column"].ToString() + ":";
TextBox txt = new TextBox();
txt.ID = "txt" + dr["id"].ToString();
}
You have to push it into !IsPostBack
On saving you have to take all IDs into some array or list, and use foreach array:
foreach (int id in id_array){
command.Parameters.AddWithValue("#"+param+id.ToString(), (TextBox)(Page.FindControlById("txt"+id.ToString())).Text);
}
But you also have to think about your sql_query (in code-behind or stored procedure, make it responsive, depending on params number).
Hope it helps
I have Image in ItemTemplate that will be changing according to Username (ie lblPostedBy.Text). I have written code in onItemCommand of repeater control in C# Asp.net 4.0. But not working. Will you please help me.
protected void myrepeater_ItemCommand1(object source, RepeaterCommandEventArgs e)
{
// Actually lblPostedBy is a linkbutton and lblPostedBy.Text is 'username of the commenter'.
LinkButton lblPostedBy = (LinkButton)e.Item.FindControl("lblPostedBy");
con.Open();
cmd.CommandText = "select image from " + lblPostedBy.Text + " where id=1";
// 'image' column in table stores path of image like '~/image/image1.jpg'
cmd.Connection = con;
string imageurl = (string)cmd.ExecuteScalar();
con.Close();
Image Image1 = (Image)e.Item.FindControl("Image1");
Image1.ImageUrl = imageurl;
}
and
<asp:Repeater ID="myrepeater" runat="server"
onitemcommand="myrepeater_ItemCommand1">
<HeaderTemplate>
<table width="100%" style="font: 8pt verdana">
<tr style="background-color:#3C78C3">
<th>NEWS FEED</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td valign="top">
<asp:Image ID="Image1" runat="server" Height="50px" Width="50px" />
<asp:LinkButton ID="lblPostedBy" runat="server" onclick="lblPostedBy_Click" Text='<%#DataBinder.Eval(Container,"DataItem.postedby") %>' />   says : <br />
<asp:TextBox id="txtPost" runat="server" Width="100%" textmode="multiline" text='<%#DataBinder.Eval(Container,"DataItem.scraps")%>' ReadOnly="True" BackColor="#EFF3FB" BorderStyle="None"></asp:TextBox>
<%#DataBinder.Eval(Container,"DataItem.scraptime") %>
<br />
<asp:TextBox ID="TextBox2" runat="server" Visible="False" Width="80%"></asp:TextBox>
<asp:Button ID="btnDoneComment" runat="server" Text="Done" Visible="False" onclick="btnDoneComment_Click"/>
<br />
<hr style="border:dashed 1px blue" />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
Thanks in Advance,
Regards,
Nikhil
Instead of "cmd.CommandText = "select image from " + lblPostedBy.Text;"
Shouldn't it be
cmd.CommandText = "select image from TableName where pby = '" + lblPostedBy.Text + "'";
Better yet, add a parameter
cmd.CommandText = "select image from tablename where pby = #pby"
cmd.Parameters.Add(new SalParameter("#pby", lblPostedBy.Text);