I have a GridView that lists data from my mysql database table. In addition, I created two TemplateFields to the GridView. The first TemplateField displays the data from database tables and the second TemplateView contains 1x asp:TextBox (a.k.a quantity) and 2x asp:Buttons (a.k.a +/- buttons which change the value inside the quantity TextBox. In addition to binding the GridView on PageLoad event, I also have a search TextBox which filters the rows displayed in the GridView. Here is the code behind for the search GridView TextBox:
private void SearchProducts()
{
string constr = ConfigurationManager.ConnectionStrings["default"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
using (MySqlCommand cmd = new MySqlCommand())
{
string sql = "SELECT logic_code,description,image_location,product_group,supplier_number,sequence,unit_code,unit_of_price,location,sales_date,price_pref,special_price,in_stock,total_inventory,new_products FROM products";
if (!string.IsNullOrEmpty(txtSearch.Text.Trim()))
{
sql += " WHERE description LIKE " + "'%" + txtSearch.Text + "%'";
}
cmd.CommandText = sql;
cmd.Connection = con;
using (MySqlDataAdapter sda = new MySqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
dt.Columns.Add(new DataColumn("QUANTITY"));
GridView1.DataBind();
//TextBox qty4 = GridView1.FindControl("qty_ordered") as TextBox;
// for(int i = 0; i < GridView1.Rows.Count; i++)
//{
// Label test222 = (Label)GridView1.Rows[i].FindControl("test2");
// TextBox qty2 = (TextBox)GridView1.Rows[i].FindControl("qty_ordered");
// if (ViewState["purchased"] != null)
// {
// qty2.Text = ViewState["purchased"].ToString();
// }
// //test222.Text = qty2.Text;
//}
}
}
}
//foreach(GridViewRow rows in GridView1.Rows)
{
//Label test22 = rows.FindControl("test2") as Label;
//TextBox qty = rows.FindControl("qty_ordered") as TextBox;
//if (ViewState["purchased"] != null)
//{
//qty.Text = ViewState["purchased"].ToString();
//}
}
}
First I tried saving each Rows TextBox.Text to ViewState but wasn't successful, then I tried dynamically adding a new column to DataTable before DataBind() but that also went south... The Buttons (+/-) and TextBox work fine when PostBack is from the buttons themselves. However, as soon as I filter the GridView using the c# code above, The TextBoxes all turn back to "0" and lose their values. I think that adding the new column dynamically is the way to go, I'm just not sure how to save/update the values without creating EditTemplateFields.
Here is my asp.net code for the GridView:
<asp:GridView id="GridView1" EnableViewState="true" AutoGenerateColumns="false" PageSize="100" ShowHeader="false" DataKeyNames="logic_code" AllowPaging="true" runat="server" Style="width:100%;margin-top:45px;">
<Columns>
<asp:BoundField DataField="QUANTITY" runat="server" readonly="true" />
<asp:TemplateField HeaderText="Product_Template" runat="server">
<ItemTemplate>
<asp:label id="supplier_number" runat="server" Style="font-weight:bold;font-size:28px;" Text='<%# Eval("supplier_number")%>' /> <asp:label id="total_inventory" runat="server" Text='<%# Eval("total_inventory")%>' Style="float:right;" />
<br />
<asp:label id="sequence" runat="server" Text='<%# Eval("sequence")%>' Style="float:right;" />
<br />
<asp:Image id="product_image" runat="server" Height="320px" Width="320px" ImageUrl='<%# Eval("image_location")%>' />
<br />
<asp:label id="product_description" runat="server" Text='<%# Eval("description")%>' Style="white-space:nowrap;" />  <asp:label id="unit_of_price" runat="server" Text='<%# Eval("unit_of_price")%>' Style="float:right;font-size:10px;margin-top:16px;margin-right:5px;margin-left:1px;" /><asp:label id="price_pref" runat="server" Text='<%# "$" + Eval("price_pref")%>' Style="float:right;font-size:22px;font-weight:bold;" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product_Template1" runat="server" ItemStyle-Width="150px">
<ItemTemplate runat="server">
<asp:Button id="add" runat="server" Text="+" Width="45px" Style="float:right;" OnClick="addClicked" autopostback="true" UseSubmitBehavior="true"></asp:Button> <asp:Button id="subtract" runat="server" Text="-" Style="float:right;" OnClick="subtractClicked" autopostback="true" UseSubmitBehavior="true" Width="45px"></asp:Button>
<asp:TextBox id="qty_ordered" runat="server" Text="0" Enabled="false" Style="float:right;" Width="57px" EnableViewState="true" ReadOnly="true" />
<asp:Label id="unit_display" runat="server" Style="float:right;" />
<asp:Label id="sequenceID" runat="server" Text='<%# Eval("sequence")%>' Visible="false" Enabled="false" />
<asp:Label id="unit_code1" runat="server" Text='<%# Eval("unit_code")%>' Visible="false" Enabled="false" />
<asp:Label id="supplier_no" runat="server" Text='<%# Eval("supplier_number")%>' Visible="false" Enabled="false" />
<asp:Label id="total_inventory1" runat="server" Text='<%# Eval("total_inventory")%>' Visible="false" Enabled="false" />
<asp:Label id="logic_code1" runat="server" Text='<%# Eval("logic_code")%>' Visible="false" Enabled="false" />
<asp:Label id="unit_of_price1" runat="server" Text='<%# Eval("unit_of_price")%>' Visible="false" Enabled="false" />
<asp:Label id="price_pref1" runat="server" Text='<%# Eval("price_pref")%>' Visible="false" Enabled="false" />
<asp:Label id="special_price1" runat="server" Text='<%# Eval("special_price")%>' Visible="false" Enabled="false" />
<asp:Label id="description1" runat="server" Text='<%# Eval("description")%>' Visible="false" Enabled="false" />
<asp:Label id="tester" runat="server" Text='<%# Eval("description")%>' Visible="false" Enabled="false" />
<asp:Label id="test2" runat="server" Visible="true" Enabled="false" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here is the code behind for how I populate the GridView on PageLoad when the GridView is not getting filtered by the search box:
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["default"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
con.Open();
using (MySqlCommand cmd = new MySqlCommand("SELECT logic_code,description,image_location,product_group,supplier_number,sequence,unit_code,unit_of_price,location,sales_date,price_pref,special_price,in_stock,total_inventory,new_products FROM products"))
{
using (MySqlDataAdapter da = new MySqlDataAdapter())
{
cmd.Connection = con;
da.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
da.Fill(dt);
GridView1.DataSource = dt;
dt.Columns.Add(new DataColumn("QUANTITY", System.Type.GetType("System.Double")));
GridView1.DataBind();
con.Close();
}
}
}
}
}
And PageLoad is here:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
BindGrid();
}
if (string.IsNullOrEmpty(txtSearch.Text))
{
//txtSearch.Attributes.Add("CssStyle", "cursor");
txtSearch.Attributes.Add("placeholder", " Showing All Products");
}
//foreach(GridViewRow row in GridView1.Rows)
//{
// if (IsPostBack)
// {
// if (ViewState["purchased"].ToString() != null)
// {
// qty.Text = ViewState["purchased"].ToString();
// }
// }
//}
}
I also have EnableViewState = "true" at the top of page.
***Note: with the code below on each button (+/-), the ViewState seems to save fine as my labels get populated appropriately by reading the ViewState even when postback. However, the values of the labels (ViewState value) get reset once I call the private void SearchProducts()
for(int i = 0; i < GridView1.Rows.Count; i++)
{
Label test222 = (Label)GridView1.Rows[i].FindControl("test2");
TextBox qty2 = (TextBox)GridView1.Rows[i].FindControl("qty_ordered");
ViewState["purchased"] = qty2.Text;
test222.Text = ViewState["purchased"].ToString();
}
and heres 2 snapshots: (as you can see, when I enter "Benus" inside the search textbox, the gridview gets filtered correctly, but all the TextBox values gets reset to "0")
Related
I have ImageButton Inside ItemTemplate in GridView I want to change Image Url "Image source" based on condition that I have prepared before. In short when I click on the ImageButton, change it's image source "For the imageButton" based on the condition I have. Here is the code I have below:
ASP.NET GridView code:
<asp:GridView ID="GridView1" BorderStyle="None" GridLines="None" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="photo_id" HeaderText="photo_id" InsertVisible="False" ReadOnly="True" SortExpression="photo_id" ItemStyle-CssClass="hiddencol" HeaderStyle-CssClass="hiddencol"/>
<asp:TemplateField HeaderText="photo_path" SortExpression="photo_path">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("photo_path") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<div class="container-md">
<div class="container">
<asp:Image ID="Image8" runat="server" ImageUrl='<%# Eval("photo_path") %>' CssClass="mx-auto d-block - responsive"/>
<div class="centered">
<asp:ImageButton ID="img_like" CssClass="os" runat="server" ImageUrl="~/images/like.png" OnClick="img_like_Click"></asp:ImageButton>
</div>
</div>
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="user_id" HeaderText="user_id" SortExpression="user_id" ItemStyle-CssClass="hiddencol" HeaderStyle-CssClass="hiddencol"/>
<asp:BoundField DataField="photo_likes" HeaderText="photo_likes" SortExpression="photo_likes" ItemStyle-CssClass="hiddencol" HeaderStyle-CssClass="hiddencol"/>
</Columns>
</asp:GridView>
Code Behind "C#" With the If Statement condition:
protected void img_like_Click(object sender, ImageClickEventArgs e)
{
ImageButton btn = (ImageButton)sender;
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
if (isPhotoLiked(Convert.ToInt32(gvr.Cells[0])))
{
// CHANGE IMAGE TO FILLED HEART IF TRUE
} else
{
// CHANGE IMAGE TO EMPTY HEART IF FALSE
}
}
The method that generates the condition if you need it:
public bool isPhotoLiked(int photoId)
{
bool isLiked = false;
SqlConnection con = new SqlConnection("server=DESKTOP-N1LLATD\\SQLEXPRESS;database=final;integrated security=sspi");
string sql = "select isLiked from Likes where photo_id=#photo_id";
SqlCommand cmd_add = new SqlCommand(sql, con);
cmd_add.Parameters.AddWithValue("#photo_id", photoId);
SqlDataReader read;
con.Open();
read = cmd_add.ExecuteReader();
if (read.HasRows)
{
if (read.Read())
{
isLiked = Convert.ToBoolean(read["isLiked"].ToString());
con.Close();
}
}
return isLiked;
}
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
Here is the HTML markup of the gridview.I mean aspx page
<asp:GridView ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false"
OnRowCreated="Gridview1_RowCreated" Height="145px">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Header 1">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 2">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 3">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true" DataTextField="CURRENCY_NAME"
DataValueField="CURRENCY_ID">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 4">
<ItemTemplate>
<asp:DropDownList ID="DropDownList2" runat="server" AppendDataBoundItems="true" DataTextField="BRAND_NAME"
DataValueField="BRAND_ID">
</asp:DropDownList>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click">Remove</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="BtnSave" runat="server" Text="Save All" OnClick="BtnSave_Click" />
<asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>`
Here is the code behind to save the data into the database
private void InsertRecords(StringCollection sc)
{
StringBuilder sb = new StringBuilder(string.Empty);
string[] splitItems = null;
const string sqlStatement = "INSERT INTO GridViewDynamicData (Field1,Field2,Field3,Field4) VALUES";
foreach (string item in sc)
{
if (item.Contains(","))
{
splitItems = item.Split(",".ToCharArray());
sb.AppendFormat("{0}('{1}','{2}','{3}','{4}'); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2], splitItems[3]);
}
}
using (OracleConnection strConn = GetConnection())
{
strConn.Open();
OracleCommand cmd = new OracleCommand(sb.ToString(), strConn);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
lblMessage.Text = "Records successfully saved!";
}
}
protected void BtnSave_Click(object sender, EventArgs e)
{
int rowIndex = 0;
StringCollection sc = new StringCollection();
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the TextBox values
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[3].FindControl("DropDownList1");
DropDownList ddl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[4].FindControl("DropDownList2");
//get the values from TextBox and DropDownList
//then add it to the collections with a comma "," as the delimited values
sc.Add(string.Format("{0},{1},{2},{3}", box1.Text, box2.Text, ddl1.SelectedItem.Text, ddl2.SelectedItem.Text));
rowIndex++;
}
//Call the method for executing inserts
InsertRecords(sc);
}
}
}
My database table is here
CREATE TABLE ERP.GRIDVIEWDYNAMICDATA
(
FIELD1 VARCHAR2(500 BYTE),
FIELD2 VARCHAR2(500 BYTE),
FIELD3 VARCHAR2(500 BYTE),
FIELD4 VARCHAR2(500 BYTE)
)
When I am running this project it is showing error "ORA-00911: invalid character". I don't know what is wrong. Any help will be appreciated.
I am not having enough reputation to comment, so I am posting my research as an answer.
Most probable cause is using ; in query building.
Remove ;(semi-colon) from the end of SQL string.
From the SQL query you are building from the code.
With semicolon (May causing the error)
sb.AppendFormat("{0}('{1}','{2}','{3}','{4}'); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2], splitItems[3]);
Without Semicolon (Should try this)
sb.AppendFormat("{0}('{1}','{2}','{3}','{4}') ", sqlStatement, splitItems[0], splitItems[1], splitItems[2], splitItems[3]);
Or
Your string may not have straight ' single quotes. Try to write that again. (It seems OK though in your code posted along with question. But nothing wrong in verifying.)
References:
ORA-00911: invalid character
https://community.oracle.com/thread/2511511
http://www.oracle.com/webfolder/technetwork/tutorials/obe/db/hol08/dotnet/getstarted-c/getstarted_c_otn.htm
I have a grid view and i need to update it with RowUpdating event, but after updating the new values did not appear, database update with the old values.
here is my code
protected void gvContactInfo_RowEditing(object sender, GridViewEditEventArgs e)
{
gvContactInfo.EditIndex = e.NewEditIndex;
bindingGVContacts(int.Parse(ddlfilterforContact.SelectedValue.ToString()));
}
protected void gvContactInfo_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label lbl = ((Label)gvContactInfo.Rows[e.RowIndex].FindControl("lblContactidno"));
DropDownList ddl = ((DropDownList)gvContactInfo.Rows[e.RowIndex].FindControl("ddlInfoType"));
TextBox txtinfo = ((TextBox)gvContactInfo.Rows[e.RowIndex].FindControl("txtValueE"));
TextBox txtext = ((TextBox)gvContactInfo.Rows[e.RowIndex].FindControl("txtExt"));
string queryContactInfo = "update tblContactInfo set ContactInfoType='"+ddl.SelectedItem.Text+"',ContactInfo='"+txtinfo.Text+"',Ext='"+txtext.Text+"' where ContactID=" + int.Parse(lbl.Text.Trim()) + "";
Connection = new SqlConnection(ConnString);
Connection.Open();
SqlCommand cmd = new SqlCommand(queryContactInfo, Connection);
cmd.ExecuteNonQuery();
Connection.Close();
gvContactInfo.EditIndex = -1;
bindingGVContacts(int.Parse(ddlfilterforContact.SelectedValue.ToString()));
}
protected void gvContactInfo_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvContactInfo.EditIndex = -1;
bindingGVContacts(int.Parse(ddlfilterforContact.SelectedValue.ToString()));
}
my databinding code is as follows:
public void bindingGVContacts(int contactID)
{
int contactID1 = contactID;
string queryContactInfo = "SELECT * FROM tblContactInfo where ContactID=" + contactID1 + "";
Connection = new SqlConnection(ConnString);
Connection.Open();
ds = new DataSet();
DataTable dt = new DataTable();
ad = new SqlDataAdapter(queryContactInfo, ConnString);
ad.Fill(ds, "queryContactInfo");
ad.Fill(dt);
Connection.Close();
if (ds.Tables["queryContactInfo"].Rows.Count > 0)
{
gvContactInfo.Columns[0].Visible = true;
gvContactInfo.DataSource = ds.Tables["queryContactInfo"];
gvContactInfo.DataBind();
gvContactInfo.Columns[0].Visible = false;
foreach (GridViewRow grow in gvContactInfo.Rows)
{
Label lbl = ((Label)grow.FindControl("lblContactidno"));
DropDownList ddl = ((DropDownList)grow.FindControl("ddlInfoType"));
DataRow[] dr = dt.Select("ContactNoID=" + lbl.Text.Trim() + "");
if (dr.Length != 0)
{
ddl.SelectedItem.Selected = false;
if (ddl.Items.FindByText(dr[0]["ContactInfoType"].ToString()) != null)
ddl.Items.FindByText(dr[0]["ContactInfoType"].ToString()).Selected = true;
}
}
}
else
{
DataRow dr = dt.NewRow();
dt.Rows.Add(dr);
gvContactInfo.DataSource = dt;
gvContactInfo.DataBind();
gvContactInfo.Rows[0].Visible = false;
}
}
here is my aspx code of gridview:
<asp:GridView runat="server" ID="gvContactInfo" ShowHeader="true" ShowHeaderWhenEmpty="true" Enableviewstate="true"
AutoGenerateColumns="false" ShowFooter="true" OnRowEditing="gvContactInfo_RowEditing" OnRowUpdating="gvContactInfo_RowUpdating" OnRowCancelingEdit="gvContactInfo_RowCancelingEdit" OnRowCommand="gvContactInfo_RowCommand"
CssClass=" CategoriesTable table table-striped table-bordered CategoriesTable1"
onrowdatabound="gvContactInfo_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Value" ItemStyle-Width="5%">
<ItemTemplate>
<asp:Label ID="lblContactidno" runat="server" Text='<%#Eval("ContactNoID")%>' Font-Bold="true"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="INFO Type" ItemStyle-Width="5%">
<ItemTemplate>
<asp:DropDownList ID="ddlInfoType" runat="server">
<asp:ListItem Value="Address" Text="Address"></asp:ListItem>
<asp:ListItem Value="Email-Personal" Text="Email-Personal"></asp:ListItem>
<asp:ListItem Value="Email-Work" Text="Email-Work"></asp:ListItem>
<asp:ListItem Value="Phone-Home" Text="Phone-Home"></asp:ListItem>
<asp:ListItem Value="Phone-Work" Text="Phone-Work"></asp:ListItem>
<asp:ListItem Value="Phone-Mobile" Text="Phone-Mobile"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlInfoType" runat="server">
<asp:ListItem Value="Address" Text="Address"></asp:ListItem>
<asp:ListItem Value="Email-Personal" Text="Email-Personal"></asp:ListItem>
<asp:ListItem Value="Email-Work" Text="Email-Work"></asp:ListItem>
<asp:ListItem Value="Phone-Home" Text="Phone-Home"></asp:ListItem>
<asp:ListItem Value="Phone-Work" Text="Phone-Work"></asp:ListItem>
<asp:ListItem Value="Phone-Mobile" Text="Phone-Mobile"></asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Value" ItemStyle-Width="5%">
<ItemTemplate>
<asp:TextBox ID="txtValue" runat="server" Text='<%#Eval("ContactInfo")%>'></asp:TextBox>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtValue" runat="server" Text=""></asp:TextBox>
</FooterTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtValueE" runat="server" Text='<%#Eval("ContactInfo")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Extension" ItemStyle-Width="5%">
<ItemTemplate>
<asp:TextBox ID="txtExtension" runat="server" Text='<%#Eval("Ext")%>'></asp:TextBox>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtExtension1" runat="server" Text=""></asp:TextBox>
</FooterTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtExt" runat="server" Text='<%#Eval("Ext")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action" ItemStyle-Width="5%">
<ItemTemplate>
<asp:LinkButton runat="server" CommandName="Edit" CausesValidation="false">Edit</asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton runat="server" CommandName="Update" CausesValidation="false">Update</asp:LinkButton>
<asp:LinkButton runat="server" CommandName="Cancel">Cancel</asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
<asp:Button runat="server" Text="ADD" CommandName="Insert"></asp:Button>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Please provide me a solution.
Just check whether you are getting the new values in gvContactInfo_RowUpdating change event using break points
Set a debugger and check if you are passing the correct (new) value to your sql query string, and use try-catch block to catch any exception when updating.
Also, it is not a good idea to build sql query using string. You should use Parameter to prevent SQL-Injection.
This example shows what could happen with SQL injection.
And this example shows how you can prevent SQL injection in C# using Parameter
Instead of reading the old values directly using the FindControl option like,
Label lbl = ((Label)gvContactInfo.Rows[e.RowIndex].FindControl("lblContactidno"));
you should be using the GridViewUpdateEventArgs.NewValues Property property to get all the new values as key/value pair.
string lblStr = e.NewValues[0].ToString(); //lblContactidno
EDIT
You are reading the existing values of your control using the FindControl method in the Row_Updating event. The problem is that your new values hasn't been updated yet and it's in the process to do so. Hence, it's pulling out the old values. Both old & New values are stored in the event GridViewUpdateEventArgs as key/value pair. So you have to get the new values from there [NewValues property]. The code I have suggested here is to read the value for your label only. check if you're getting the new value for it or not as it's based on the assumption that the label is the first control in the grid.
i got another way to update i.e with the help of RowCommand method
protected void gvContactInfo_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Update"))
{
GridViewRow gvr = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
int RowIndex = gvr.RowIndex;
Label lbl = ((Label)gvContactInfo.Rows[RowIndex].FindControl("lblContactidno"));
DropDownList ddl = ((DropDownList)gvContactInfo.Rows[RowIndex].FindControl("ddlInfoType"));
TextBox txtinfo = ((TextBox)gvContactInfo.Rows[RowIndex].FindControl("txtValueE"));
TextBox txtext = ((TextBox)gvContactInfo.Rows[RowIndex].FindControl("txtExt"));
string queryContactInfo = "update tblContactInfo set ContactInfoType='" + ddl.SelectedItem.Text + "',ContactInfo='" + txtinfo.Text + "',Ext='" + txtext.Text + "' where ContactNoID=" + int.Parse(lbl.Text.Trim()) + "";
Connection = new SqlConnection(ConnString);
Connection.Open();
SqlCommand cmd = new SqlCommand(queryContactInfo, Connection);
cmd.ExecuteNonQuery();
Connection.Close();
gvContactInfo.EditIndex = -1;
}
}
I have sent value through querystring to this Page. After that I am Unable to get Edit Mode on modechanging event. When I click Edit button, simply it postbacks and nothing happens. If Clicked edit second time it gives Error :
(Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request.)
Please tell me where I am wrong.
Source Code -
<asp:FormView ID="formview1" runat="server" AllowPaging="true" Caption="FireBrigade" DataKeyNames="FireBrigadeID" OnModeChanging="formview1_ModeChanging"
OnPageIndexChanging="formview1_PageIndexChanging">
<ItemTemplate>
FireBrigade ID :<asp:Label ID="lblFID" runat="server" Text='<%# Eval("FireBrigadeID") %>'></asp:Label><br />
Name :<asp:Label ID="Label3" runat="server" Text='<%# Eval("FBName") %>'></asp:Label><br />
LatLong:<asp:Label ID="Label1" runat="server" Text='<%# Eval("LatLng") %>'></asp:Label><br />
Address: <asp:Label ID="Label2" runat="server" Text='<%# Eval("Address") %>'></asp:Label><br />
Contact: <asp:Label ID="Label4" runat="server" Text='<%# Eval("ContactNumber") %>'></asp:Label><br />
<asp:LinkButton ID="EditButton" Text="Edit" CommandName="Edit" RunAt="server"/>
</ItemTemplate>
<EditItemTemplate>
FireBrigade ID :<asp:TextBox ID="txtFID" runat="server" Text='<%# Bind("FireBrigadeID") %>'></asp:TextBox><br />
Name :<asp:TextBox ID="txtname" runat="server" Text='<%# Bind("FBName") %>'></asp:TextBox>
LatLong:<asp:TextBox ID="txtlatlong" runat="server" Text='<%# Bind("LatLng") %>'></asp:TextBox><br />
Address: <asp:DropDownList ID="ddlAddress" runat="server" OnDataBound="ddlAddress_DataBound" AppendDataBoundItems="true">
<asp:ListItem Text="Select" Value="0"></asp:ListItem>
</asp:DropDownList> <br />
Contact: <asp:TextBox ID="txtcontact" runat="server" Text='<%# Bind("ContactNumber") %>'></asp:TextBox><br />
<asp:LinkButton ID="UpdateButton"
Text="Update"
CommandName="Update"
runat="server" />
<asp:LinkButton ID="CancelUpdateButton"
Text="Cancel"
CommandName="Cancel"
runat="server" />
</EditItemTemplate>
</asp:FormView>
C# Code -
public partial class Fifthpage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lblshow.Text = Request.QueryString["q"].ToString();
Dataset ds = new Dataset();
ds = bind();
da.Fill(ds);
formview1.DataSource = ds;
formview1.DataBind();
}
}
public DataSet bind()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=SYSTEM-PC;Initial Catalog=DB;Integrated Security=True";
SqlCommand cmd = new SqlCommand("select * from FireBrigade",con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
protected void ddlAddress_DataBound(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds = bind();
List<string> ls = new List<string>();
foreach (ListItem lst in ds.Tables[0].Rows)
{
//lst.Value = ds.Tables[0].Rows[0]["Address"].ToString();
ls.Add(ds.Tables[0].Rows[0]["Address"].ToString());
}
DropDownList ddladd = (DropDownList)formview1.FindControl("ddlAddress");
ddladd.DataSource = ls;
}
protected void formview1_ModeChanging(object sender, FormViewModeEventArgs e)
{
formview1.ChangeMode(e.NewMode);
bind();
}
protected void formview1_PageIndexChanging(object sender, FormViewPageEventArgs e)
{
formview1.PageIndex = e.NewPageIndex;
bind();
}
}
You should reassign the DataSource of FormView after editing, so just change your code as follow
protected void formview1_ModeChanging(object sender, FormViewModeEventArgs e)
{
formview1.ChangeMode(e.NewMode);
formview1.DataSource = bind();
formview1.DataBind();
}