Populate DropDownList in DataList in ASPX - c#

I'm working in a Quiz Page where users can access and answers some questions. The problem I'm facing is when I want to display the possible answers of the questions. I want to display the options in a dropdownlist. I already have the questions in a datalist. Are there any ideas of how can I do it?
This is how it looks:
(In the arrows that I placed is where I want to display the options)
This is what users see
Here is what I have:
A FormQuiz.aspx:
<body style="background-color: #0f5298">
<form id="form1" runat="server">
<nav class="auto-style2" style="background-color: #d5f3fe">
<div class="auto-style3">
<a class="navbar-brand" href="#">
<img src="logo.png" alt="" class="auto-style1" />
Quiz
</a>
</div>
</nav>
<div class="card">
<asp:Label ID="LabelName" runat="server" Text="Seleccione un Quiz:" CssClass="lbl"></asp:Label>
<asp:DropDownList ID="DropDownList1" runat="server" CssClass="ddl" AppendDataBoundItems="true" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" >
<asp:ListItem Text="--- Seleccione ----" Value=" " />
</asp:DropDownList>
<asp:Label ID="Label1" runat="server" Text="Instrucciones" CssClass="lbl"></asp:Label>
<asp:Label ID="LabelInstrucciones" runat="server" CssClass="I"></asp:Label>
<asp:Panel ID="Panel1" runat="server" CssClass="panelQ">
<asp:Label ID="Label2" runat="server" CssClass="section"></asp:Label>
<asp:DataList ID="DataList1" runat="server" CssClass="datalist">
<ItemTemplate>
<div style="margin-top: 2%">
<asp:Label ID="Label2" runat="server" Text='<%#Eval("Description") %>'></asp:Label>
</div>
<asp:DropDownList ID="DropDownOptions" runat="server" Width="200px" AppendDataBoundItems="true" AutoPostBack="true" DataSourceID="dsOptions" DataTextField="Options" DataValueField="Id">
<asp:ListItem></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:DataList>
</asp:Panel>
</div>
</form>
</body>
This is how I get the questions in FormQuiz.aspx.cs:
public void SelectedSectionsTitlesQuestions(int id)
{
using (SqlConnection con = new SqlConnection(connectionstring))
{
con.Open();
string querySection = #"SELECT Mant.Sections.Name
FROM Mant.Quizzes
INNER JOIN Mant.Questions ON Mant.Quizzes.Id = Mant.Questions.Quiz_Id
INNER JOIN Mant.Sections ON Mant.Questions.Section_Id = Mant.Sections.Id
WHERE Mant.Quizzes.Id =" + id;
string queryQuestion = #"SELECT Mant.Questions.Description
FROM Mant.Quizzes
INNER JOIN Mant.Questions ON Mant.Quizzes.Id = Mant.Questions.Quiz_Id
WHERE Mant.Quizzes.Id =" + id;
SqlDataAdapter ad2 = new SqlDataAdapter(querySection, con);
DataSet ds2 = new DataSet();
ad2.Fill(ds2);
Label lblsection = (Label)FindControl("Label2");
lblsection.Text = ds2.Tables[0].Rows[0]["Name"].ToString(); ;
DataList datalistQuestions = (DataList)FindControl("DataList1");
SqlDataAdapter ad = new SqlDataAdapter(queryQuestion, con);
DataSet ds = new DataSet();
ad.Fill(ds);
datalistQuestions.DataSource = ds;
datalistQuestions.DataBind();
FillDropdown();
con.Close();
}
}
This is how I populate the dropdown with a SqlDataSource:
public void FillDropdown()
{
using (SqlConnection con = new SqlConnection(#"Server =hncrsap-sql01; Database=HEDS;User Id = sa; Password=Lear2005; MultipleActiveResultSets=true;"))
{
con.Open();
List<int> Types = new List<int>(TypeQuestionsId());
for(int x=0; x < Types.Count(); x++)
{
int TQuestions_Id = Types[x];
string queryTypeQuestion = #"SELECT TypeQuestions_Id
FROM Mant.Questions
WHERE Quiz_Id=" + id_Quiz +
"AND TypeQuestions_Id=" + TQuestions_Id;
SqlCommand SelectCommand = new SqlCommand(queryTypeQuestion, con);
SqlDataReader myreader;
myreader = SelectCommand.ExecuteReader();
while (myreader.Read())
{
string querySelectOptions = #"SELECT Options, Id
FROM Mant.AnswerOptions
WHERE TypeQuestions_Id=" + TQuestions_Id;
SqlDataSource dsOptions = new SqlDataSource();
dsOptions.ID = "dsOptions";
this.Page.Controls.Add(dsOptions);
dsOptions.ConnectionString = "Server =hncrsap-sql01; Database=HEDS;User Id = sa; Password=Lear2005; MultipleActiveResultSets=true;";
dsOptions.SelectCommand = querySelectOptions;
}
}
con.Close();
}
// return values;
}
But I got this error in the SelectedSectionsTitlesQuestions method

You can configure another SqlDataSource and bind it to your drop-down list.
<asp:DropDownList ID="ddlEmployees" runat="server" DataSourceID="SqlDataSource1"
DataTextField="EmployeeName" DataValueField="EmployeeID" AppendDataBoundItems="true">
<asp:ListItem Text="Please select" Value="" />
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DB_9EF896_weddingConnectionString %%>"
SelectCommand="SELECT (FirstName + ' ' + LastName) AS EmployeeName, EmployeeID FROM Employees">
</asp:SqlDataSource>
Result

Related

Repeater Control, Insert

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();
}
}

Fill multiple textboxes after selecting two columns DropDownList in ASP.NET

I have a DropDownList which contains the two columns one is CardCode and other is CardName and that is linked to a SQL database. It currently shows a list of CardCode + List of Cardname. I am trying to make it so that once a CardCode + CardName is selected from the two columns dropdownlist, multiple textboxes are automatically filled (such as CardNum, CntctPerson,ListNum etc). I am able to automatically fill the data from selecting only CardCode now I want to show the related row to the CardCode + CardName dropdown list, I do not know how to fill the other rows by selecting 2 column's dropdown list(CardCode + CardName) .How can i do this? Thanks In Advance
Here is my aspx.cs Code below
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;
namespace StackOver
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadOptions();
}
}
protected void LoadOptions()
{
DataTable CardCode = new DataTable();
SqlConnection connection = new SqlConnection("my connection string");
using (connection)
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT CardCode,CardName, Address, CntctPrsn FROM OCRD", connection);
adapter.Fill(CardCode);
DropDownList1.DataValueField = "CardCode";
DropDownList1.DataTextField = "CardCode";
DropDownList1.DataBind();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = DropDownList1.SelectedItem.Value;
SqlConnection connection = new SqlConnection("my connection string");
using (connection)
{
SqlCommand theCommand = new SqlCommand("SELECT CardCode, CardName, Address, CntctPrsn FROM OCRD WHERE CardCode = #CardCode", connection);
connection.Open();
theCommand.Parameters.AddWithValue("#CardCode", selected);
theCommand.CommandType = CommandType.Text;
SqlDataReader theReader = theCommand.ExecuteReader();
if (theReader.Read())
{
// Get the first row
// theReader.Read();
// Set the text box values
this.TextBox1.Text = theReader.GetString(0);
this.TextBox2.Text = theReader.GetString(1);
this.TextBox3.Text = theReader.GetString(2);
// this.TextBox3 = reader.IsDBNull(TextBox3Index) ? null : reader.GetInt32(TextBox3Index)
// GenreID = reader.IsDBNull(genreIDIndex) ? null : reader.GetInt32(genreIDIndex)
this.TextBox4.Text = theReader.GetString(3);
// TextBox5.Text = theReader.GetString(4);
// TextBox6.Text = theReader.GetString(5);
// TextBox7.Text = theReader.GetString(6);
}
connection.Close();
}
}
public object TextBox3Index { get; set; }
}
}
And also this is my .aspx code
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="StackOver._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
Welcome to ASP.NET!
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
DataSourceID="SqlDataSource1" DataTextField="CardCode"
DataValueField="CardName"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:myconnectionstring %>"
SelectCommand="SELECT [CardCode] + '----' + [CardName] as CardCode, CardName,[Address], [CntctPrsn] FROM [OCRD]">
</asp:SqlDataSource>
</h2>
<br />
<br />
<p>
</p>
<p>
</p>
<p>
Business Partner Code :
<asp:TextBox ID="TextBox1" runat="server" Width="192px" ></asp:TextBox>
</p>
<p>
Business Partner Name :
<asp:TextBox ID="TextBox2" runat="server" Width="192px" ></asp:TextBox>
</p>
<p>
Address :
<asp:TextBox ID="TextBox3" runat="server" Width="196px" ></asp:TextBox>
</p>
<p>
Contact Person Name :
<asp:TextBox ID="TextBox4" runat="server" Width="196px" ></asp:TextBox>
</p>
<p>
<asp:TextBox ID="TextBox5" runat="server" ></asp:TextBox>
</p>
<p>
<asp:TextBox ID="TextBox6" runat="server" ></asp:TextBox>
</p>
<p>
<asp:TextBox ID="TextBox7" runat="server" ></asp:TextBox>
</p>
</asp:Content>
Code behind Code.
protected void LoadOptions()
{
DataTable CardCode = new DataTable();
SqlConnection connection = new SqlConnection("my connection string");
using (connection)
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT CardCode,CardName, Address, CntctPrsn FROM OCRD", connection);
adapter.Fill(CardCode);
if (CardCode.Rows.Count > 0)
{
for (int i = 0; i < CardCode.Rows.Count; i++)
{
id = CardCode.Rows[i]["CardCode"].ToString();
name = CardCode.Rows[i]["CardName"].ToString();
newName = id + " ---- " + name;
DropDownList1.Items.Add(new ListItem(newName,id));
}
}
}
}
.Aspx Code
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="StackOver._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
Welcome to ASP.NET!
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
</h2>
<br />
<br />
<p>
</p>
<p>
</p>
<p>
Business Partner Code :
<asp:TextBox ID="TextBox1" runat="server" Width="192px" ></asp:TextBox>
</p>
<p>
Business Partner Name :
<asp:TextBox ID="TextBox2" runat="server" Width="192px" ></asp:TextBox>
</p>
<p>
Address :
<asp:TextBox ID="TextBox3" runat="server" Width="196px" ></asp:TextBox>
</p>
<p>
Contact Person Name :
<asp:TextBox ID="TextBox4" runat="server" Width="196px" ></asp:TextBox>
</p>
<p>
<asp:TextBox ID="TextBox5" runat="server" ></asp:TextBox>
</p>
<p>
<asp:TextBox ID="TextBox6" runat="server" ></asp:TextBox>
</p>
<p>
<asp:TextBox ID="TextBox7" runat="server" ></asp:TextBox>
</p>

Automatically create labels based on the number of database entry's c# asp.net mssql

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" />
&nbsp&nbsp<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

Displaying specific information on aspx page using database

I am building a website with ASP.NET Web Forms, and a SQL database.
On one particular page I have a number of houses with some informations.
There are 571 houses in total.
When I click on a particular house, I want to bring up a new page with more information about that house.
All the data is coming from a table in the database.
Is there a way of knowing which house has been selected, and display the data on the new aspx page for that house?
I know I could create many separate aspx pages for each house but there are 571 houses and there would have to be 571 aspx pages. That is far too much wasted code.
When I click on the house name I want only one aspx page but I want it to know that I have selected that house and display the information for that specific one. Like its accessing the database information for that house and displays it.
The main obstacle here is knowing what house has been selected. I know how to display information from a database.
Houses.aspx
When I click a house name I want to display a page like the one below.
HouseInfo.aspx
HouseInfo.aspx.cs
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
using (SqlCommand command = new SqlCommand("SELECT Id, Name, Townland, Near, Status, Built, Description, Families FROM Houses ORDER BY Name DESC", connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
lblId.Text = reader[0].ToString();
lblName.Text = reader[1].ToString();
lblTown.Text = reader[2].ToString();
lblNear.Text = reader[3].ToString();
lblStatus.Text = reader[4].ToString();
lblBuilt.Text = reader[5].ToString();
lblDesc.Text = reader[6].ToString();
lblFam.Text = reader[7].ToString();
}
}
}
}
}
This is how I am accessing the database to display some of the info on the HouseInfo page already.
HouseInfo.aspx
<b>ID:</b> <asp:Label ID="lblId" runat="server"></asp:Label>
<br /><b>Name of House:</b> <asp:Label ID="lblName" runat="server"></asp:Label>
<br /><b>Townland:</b> <asp:Label ID="lblTown" runat="server"></asp:Label>
<br /><b>Near:</b> <asp:Label ID="lblNear" runat="server"></asp:Label>
<br /><b>Status/Public Access:</b> <asp:Label ID="lblStatus" runat="server </asp:Label>
<br /><b>Date Built:</b> <asp:Label ID="lblBuilt" runat="server"></asp:Label>
<br /><b>Description:</b> <asp:Label ID="lblDesc" runat="server"></asp:Label>
<br /><b>Associated Families:</b> <asp:Label ID="lblFam" runat="server"></asp:Label>
Houses.aspx
<%# Page Title="Houses" Language="C#" MasterPageFile="~/Master.Master" AutoEventWireup="true" CodeBehind="Houses.aspx.cs" Inherits="Houses_of_Mayo.images.Houses" EnableEventValidation="false" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script>
$(function () { setCurrentTab('tab2'); });
</script>
<div class="box">
<div>
<div class="body">
<h1>Houses</h1>
<ul id="rooms">
<asp:Repeater ID="rptData" runat="server" >
<ItemTemplate>
<li>
<a href="HouseInfo.aspx">
<img src="x" alt="img" /></a>
<h2>
<asp:Label runat="server" Text='<%# Eval("Name") %>'></asp:Label></h2>
<p>
<b>ID: </b>
<asp:Label runat="server" Text='<%# Eval("Id") %>'></asp:Label>
<br />
<b>Name of House: </b>
<asp:Label runat="server" Text='<%# Eval("Name") %>'></asp:Label>
<br />
<b>Townland: </b>
<asp:Label runat="server" Text='<%# Eval("Townland") %>'></asp:Label>
<br />
<b>Near: </b>
<asp:Label runat="server" Text='<%# Eval("Near") %>'></asp:Label>
<br />
<b>Status/Public Access: </b>
<asp:Label runat="server" Text='<%# Eval("Status") %>'></asp:Label>
<br />
<b>Date Built: </b>
<asp:Label runat="server" Text='<%# Eval("Built") %>'></asp:Label>
</p>
</li>
</ItemTemplate>
</asp:Repeater>
</ul>
<asp:Repeater ID="rptPager" runat="server">
<ItemTemplate>
<asp:LinkButton ID="lnkPage" runat="server" Text='<%#Eval("Text") %>' CommandArgument='<%# Eval("Value") %>'
style="padding:8px; margin:2px; background:#ac9e94; border:solid 1px #666; font:8pt; color:#594334; display: inline-block;"
CssClass='<%# Convert.ToBoolean(Eval("Enabled")) ? "page_enabled" : "page_disabled" %>'
OnClick="Page_Changed" OnClientClick='<%# !Convert.ToBoolean(Eval("Enabled")) ? "return false;" : "" %>'></asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
</div>
</div>
</div>
</asp:Content>
Houses.aspx.cs
private int PageSize = 5;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.GetCustomersPageWise(1);
}
}
private void GetCustomersPageWise(int pageIndex)
{
string constring = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("GetHousesPageWise", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#PageIndex", pageIndex);
cmd.Parameters.AddWithValue("#PageSize", PageSize);
cmd.Parameters.Add("#RecordCount", SqlDbType.Int, 4);
cmd.Parameters["#RecordCount"].Direction = ParameterDirection.Output;
con.Open();
IDataReader idr = cmd.ExecuteReader();
rptData.DataSource = idr;
rptData.DataBind();
idr.Close();
con.Close();
int recordCount = Convert.ToInt32(cmd.Parameters["#RecordCount"].Value);
this.PopulatePager(recordCount, pageIndex);
}
}
}
private void PopulatePager(int recordCount, int currentPage)
{
double dblPageCount = (double)((decimal)recordCount / Convert.ToDecimal(PageSize));
int pageCount = (int)Math.Ceiling(dblPageCount);
List<ListItem> pages = new List<ListItem>();
if (pageCount > 0)
{
for (int i = 1; i <= pageCount; i++)
{
pages.Add(new ListItem(i.ToString(), i.ToString(), i != currentPage));
}
}
rptPager.DataSource = pages;
rptPager.DataBind();
}
protected void Page_Changed(object sender, EventArgs e)
{
int pageIndex = int.Parse((sender as LinkButton).CommandArgument);
this.GetCustomersPageWise(pageIndex);
}
Map (HouseInfo.aspx)
HouseInfo.aspx
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script>
function initialize() {
var myLatlng = new google.maps.LatLng(53.613873, -9.668301);
var mapOptions = {
zoom: 17,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var contentString = '<div id="content">' +
'<div id="siteNotice">' +
'</div>' +
'<h2 id="firstHeading" class="firstHeading">Aasleagh Lodge</h2>' +
'<div id="bodyContent">' +
'<b>ID:</b> A1' +
'</br><b>Name:</b> Aasleagh Lodge' +
'</br><b>Townland:</b> Srahatloe' +
'</br><b>Ref:</b> 1' +
'</br><b>Latitude:</b> 53.613873' +
'</br><b>Longitude:</b> -9.668301' +
'</div>' +
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var image = 'Images/icon56.png';
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Aasleagh Lodge',
icon: image
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
HouseInfo Table
[Id] CHAR (10) NOT NULL,
[Name] NVARCHAR (MAX) NULL,
[Townland] NVARCHAR (MAX) NULL,
[Ref] INT NULL,
[Lat] FLOAT (53) NULL,
[Lng] FLOAT (53) NULL,
CONSTRAINT [PK_HouseInfo] PRIMARY KEY CLUSTERED ([Id] ASC)
There are multiple ways to do that. Best (IMO) and easiest is to use query string to pass the ID (or primary key data) of the selected house to the next web-form and display data using that value.
in this code you are sending Id of house to other page.
<a href='<%# "HouseInfo.aspx?HouseId=" + Eval("Id").ToString() %>'>
<img src="x" alt="img" /></a>
and here you are getting that Id back
string HouseId = Request.Params["HouseId"].ToString();
also in here you are filtering your data to only get that houses information
"SELECT Id, Name, Townland, Near, Status, Built, Description, Families FROM Houses WHERE Id = '" + HouseId + "' ORDER BY Name DESC"
complete code ;
HouseInfo.aspx.cs
string HouseId = Request.Params["HouseId"].ToString();
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
using (SqlCommand command = new SqlCommand("SELECT Id, Name, Townland, Near, Status, Built, Description, Families FROM Houses WHERE Id = '" + HouseId + "' ORDER BY Name DESC", connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
lblId.Text = reader[0].ToString();
lblName.Text = reader[1].ToString();
lblTown.Text = reader[2].ToString();
lblNear.Text = reader[3].ToString();
lblStatus.Text = reader[4].ToString();
lblBuilt.Text = reader[5].ToString();
lblDesc.Text = reader[6].ToString();
lblFam.Text = reader[7].ToString();
}
}
}
}
Houses.aspx
<ul id="rooms">
<asp:Repeater ID="rptData" runat="server" >
<ItemTemplate>
<li>
<a href='<%# "HouseInfo.aspx?HouseId=" + Eval("Id").ToString() %>'>
<img src="x" alt="img" /></a>
<h2>
<a href='<%# "HouseInfo.aspx?HouseId=" + Eval("Id").ToString() %>'><asp:Label runat="server" Text='<%# Eval("Name") %>'></asp:Label></a></h2>
<p>
<b>ID: </b>
<asp:Label runat="server" Text='<%# Eval("Id") %>'></asp:Label>
<br />
<b>Name of House: </b>
<asp:Label runat="server" Text='<%# Eval("Name") %>'></asp:Label>
<br />
<b>Townland: </b>
<asp:Label runat="server" Text='<%# Eval("Townland") %>'></asp:Label>
<br />
<b>Near: </b>
<asp:Label runat="server" Text='<%# Eval("Near") %>'></asp:Label>
<br />
<b>Status/Public Access: </b>
<asp:Label runat="server" Text='<%# Eval("Status") %>'></asp:Label>
<br />
<b>Date Built: </b>
<asp:Label runat="server" Text='<%# Eval("Built") %>'></asp:Label>
</p>
</li>
</ItemTemplate>
</asp:Repeater>
</ul>

Assign Gridview values to text box

I have to ask about A question in C#,Asp.net... i created 3 textbox for empid, name and Address
If i Click the "Edit Button" with manually type empid in a text box. i want to assign other two values name & Address to their textbox. then after i use update button to update
Can anyone teach me with code?
//Asp.net
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Empid" Width="50px"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:Label ID="Label2" runat="server" Text="Name" Width="50px"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<asp:Label ID="Label3" runat="server" Text="Address" Width="50px"></asp:Label>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<br />
<br />
<br />
<br />
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
<br />
</div>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="update " />
<asp:Button ID="Button2" runat="server" Text="Edit" Width="61px" />
</form>
//Cs for update button
SqlConnection conn = new SqlConnection("Data Source=s\\SQLEXPRESS;Initial catalog = sample;Integrated security=True");
SqlCommand cmd = new SqlCommand("UPDATE empdetails SET Name='" + TextBox2.Text + "',Address='" + TextBox3.Text + "' WHERE Empid ='" + TextBox1.Text + "'", conn);
conn.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT * FROM Empdetails";
GridView.DataSource = cmd.ExecuteReader();
GridView.DataBind();
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
conn.Close();
I code like this ,if i Edit Button, with entered Empid, i want other values name & Address ll assign to text box
Steps:
Get the Employee details in GridView.
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
GetEmpDetails()
End Sub
Private Sub GetEmpDetails()
SqlConnection conn = new SqlConnection("Data Source=s\\SQLEXPRESS;Initial catalog = sample;Integrated security=True");
conn.Open();
cmd.CommandText = "SELECT * FROM Empdetails";
GridView.DataSource = cmd.ExecuteReader();
GridView.DataBind();
End Sub
Add this Property AutoGenerateSelectButton="True" to the gridview in the design page.
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
AutoGenerateSelectButton="True"
CellPadding="4" >
</asp:GridView>
On the SelectedIndexChanged of the Grid get the RowIndex so that we will get the row value of the row selected.
Protected Sub GridView1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles GridView1.SelectedIndexChanged
LoadValues(GridView1.SelectedRow.RowIndex)
End Sub
Then Load the grid values to the respective textbox.
And change the values you want but don't change the ID (Highly recommended)
Then Click UpdateButton. Call Update Query there.
Load grid value again and bind it. So that you can see the change instantly.
Happy Coding..!! :)

Categories

Resources