ASP.NET C# MySql Select and Update a form - c#

Here i Got some code i tried lot of method, I just able to display the data into my form by using Select query but Am not able to update it, it updating but it just updating old value not new value i changed in textbox
Here is the form
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Editcar.aspx.cs" MasterPageFile="MasterPage2.master" Inherits ="Editcar" %>
<asp:Content ID="formContent" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<br />
<br />
<br />
<div class="row container">
<form id="form1" runat="server" class="col-md-10" action="update.aspx" methode="post" >
<asp:Table ID="GridView1" class="nav-justified" runat="server" AutoGenerateColumns="false" Height="628px" Width="763px">
<asp:TableRow>
<asp:TableCell>
<h4> Car name:</h4>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="id" runat="server" name="id" Width="301px" Text='<%# Eval("id") %>' Visible="False" CssClass="form-control"></asp:TextBox>
<asp:TextBox ID="carmake" runat="server" Font-Names="carmake" Width="301px" Text='<%# Eval("car_make") %>' CssClass="form-control"></asp:TextBox>
</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell>
<h4> Car model:</h4>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="carmodel" runat="server" name="carmodel" Text='<%# Eval("car_model") %>' Width="301px" CssClass="form-control"></asp:TextBox>
</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell>
<h4> Price: </h4>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="price" name="price" runat="server" Width="301px" CssClass="form-control"></asp:TextBox>
</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell>
<h4> Discounted Price If: </h4>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="d_price" name="d_price" runat="server" Width="301px" CssClass="form-control"/>
</asp:TableCell></asp:TableRow><asp:TableRow>
<asp:TableCell> <h4>Car image (Type url)</h4></asp:TableCell><asp:TableCell>
<asp:TextBox CssClass="form-control" ID="image" name="image" runat="server" />Just Location
</asp:TableCell></asp:TableRow><asp:TableRow>
<asp:TableCell><h4>Avilability</h4></asp:TableCell><asp:TableCell>
<asp:TextBox CssClass="form-control" ID="avail" name="avail" runat="server" />Just Location
</asp:TableCell></asp:TableRow><asp:TableRow>
<asp:TableCell><h4>Quantity</h4></asp:TableCell><asp:TableCell>
<asp:TextBox CssClass="form-control" ID="quantity" name="quantity" runat="server" />Just Location
</asp:TableCell></asp:TableRow><asp:TableRow>
<asp:TableCell>
<h4>Long description </h4>
</asp:TableCell><asp:TableCell>
<asp:TextBox ID="details" name="details" runat="server" Width="295px" CssClass="form-control" Height="81px" TextMode="MultiLine"></asp:TextBox>
</asp:TableCell></asp:TableRow><asp:TableRow>
<asp:TableCell>
<h4>Year </h4>
</asp:TableCell><asp:TableCell>
<asp:TextBox ID="year" name="year" runat="server" Width="295px" CssClass="form-control" ></asp:TextBox>
</asp:TableCell></asp:TableRow><asp:TableRow>
<asp:TableCell>
<h4>Special Discounted(0 0r 1) </h4>
</asp:TableCell><asp:TableCell>
<asp:TextBox ID="special" name="special" runat="server" Width="295px" CssClass="form-control" ></asp:TextBox>
</asp:TableCell></asp:TableRow></asp:Table><asp:Button ID="button" runat="server" Cssclass="btn btn-primary btn-lg btn-block" Text="Update the car" />
<br />
<br />
</form>
</div>
</asp:Content>
Here is the CS file
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;
using MySql.Data.MySqlClient;
public partial class Editcar : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
var id = Request.QueryString["id"];
string selectquery = "SELECT * FROM product WHERE id=" + #id;
MySqlCommand cmd = new MySqlCommand(selectquery);
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
con.Open();
cmd.ExecuteNonQuery();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
id = dr["id"].ToString();
carmake.Text = dr["car_make"].ToString();
carmodel.Text = dr["car_model"].ToString();
price.Text = dr["unitprice"].ToString();
d_price.Text = dr["discountprice"].ToString();
image.Text = dr["image"].ToString();
quality.Text = dr["quantity"].ToString();
avil.Text = dr["availability"].ToString();
details.Text = dr["details"].ToString();
year.Text = dr["year"].ToString();
special.Text = dr["special"].ToString();
}
}
}
}
Here his the update page cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using MySql.Data.MySqlClient;
public partial class AdminGroup_Update: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string constor = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
MySqlConnection conn = new MySqlConnection(constor);
var id = Request.QueryString["id"];
var carmake = Request.QueryString["carmake"];
var carmodel = Request.QueryString["carmodel"];
var price = Request.QueryString["price"];
var d_price = Request.QueryString["d_price"];
var image = Request.QueryString["image"];
var quantity = Request.QueryString["quantity"];
var avail = Request.QueryString["avail"];
var details = Request.QueryString["details"];
var year = Request.QueryString["year"];
var special = Request.QueryString["special"];
string sql = "Update product SET car_make=#carmake ,car_model=#carmodel ,UnitPrice=#price ,Discountprice=#d_price ,image=#image ,Quantity=#quality ,availability=#avil ,details=#details ,year=#year ,special=#special WHERE id= #id";
var cmd = new MySqlCommand(sql, conn);
conn.Open();
cmd.CommandType = CommandType.Text;
var param = new MySqlParameter[10];
param[0] = new MySqlParameter("#carmake", MySqlDbType.VarChar, 100);
param[1] = new MySqlParameter("#carmodel", MySqlDbType.VarChar, 100);
param[2] = new MySqlParameter("#price", MySqlDbType.VarChar, 100);
param[3] = new MySqlParameter("#d_price", MySqlDbType.VarChar, 100); // put zero if no discount
param[4] = new MySqlParameter("#image", MySqlDbType.VarChar, 300);
param[5] = new MySqlParameter("#quantity", MySqlDbType.VarChar, 300);
param[6] = new MySqlParameter("#avail", MySqlDbType.VarChar, 2);
param[7] = new MySqlParameter("#details", MySqlDbType.VarChar, 2000);
param[8] = new MySqlParameter("#year", MySqlDbType.VarChar, 4);
param[9] = new MySqlParameter("#special", MySqlDbType.VarChar, 2);
param[10] = new MySqlParameter("#id", MySqlDbType.VarChar, 2);
param[0].Value = carmake;
param[1].Value = carmodel;
param[2].Value = price;
param[3].Value = d_price;
param[4].Value = image;
param[5].Value = quality;
param[6].Value = avil;
param[7].Value = details;
param[8].Value = year;
param[9].Value = special;
param[10].Value =id;
var ex = cmd.ExecuteNonQuery();
if (ex == 1)
{
Response.Redirect("AdminList.aspx");
}
else
{
Response.Write("Error");
}
conn.Close();
}
}

Your button
<asp:Button ID="button" runat="server"
Cssclass="btn btn-primary btn-lg btn-block"
Text="Update the car" />
needs an OnClick setting and an event handler in your code-behind .cs file to handle it.
Webforms / dot net works differently from some other interactive web page frameworks in that most controls post back to the same page rather than posting to another page. So, you don't need a separate update page, and indeed won't be able to use it in the normal course of event processing.

Related

PageIndexChanging event for GridView not firing

I'm building an ASP.NET web application. I have an .ASPX page where I created a static GridView that I fill (with a SQL Server stored procedure) after the click of a button. I need to implement paging, but it doesn't work: when I click on page 2, 3 or whatever, the GridView seems to disappear.
ASPX
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="UDC.aspx.cs" Inherits="DynamicStoreWebApplication.UDC" %>
<link href="Controls.css" rel="stylesheet" type="text/css" />
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>DynamicStore Web - Unità di carico</title>
</head>
<body>
<form id="form1" runat="server">
<div runat="server">
<asp:PlaceHolder ID="PlaceHolderHeader" runat="server"></asp:PlaceHolder>
<div style="float: left; width: 10%; background: #fff2e6;">
<asp:PlaceHolder ID="PlaceHolderMenu" runat="server"></asp:PlaceHolder>
</div>
<div style="padding: 25px; padding-left: 200px; width: 90%;">
<asp:Label ID="DateFromLbl" runat="server" Text="Dal giorno: " CssClass="label"></asp:Label>
<asp:TextBox ID="DateFrom" runat="server" Width="130px" TextMode="Date" CssClass="dropdown" Font-Names="Tahoma">2000-01-01</asp:TextBox>
<asp:Label ID="DateToLbl" runat="server" Text="Al giorno: " CssClass="label"></asp:Label>
<asp:TextBox ID="DateTo" runat="server" Width="130px" TextMode="Date" CssClass="dropdown" Font-Names="Tahoma"></asp:TextBox>
<asp:Label ID="Ricerca" runat="server" Text="Ricerca: " CssClass="label"></asp:Label>
<asp:TextBox ID="Search" runat="server" Width="95px" TextMode="SingleLine"></asp:TextBox>
<asp:Label ID="Risultati" runat="server" Text="Ultimi risultati: " CssClass="label"></asp:Label>
<asp:CheckBox ID="TopResults" runat="server" EnableViewState="true" ViewStateMode="Enabled"/>
<asp:Button ID="btnSubmit" runat="server" Text="Visualizza UDC" CssClass="control-button" OnClick="btnSubmit_Click"/>
<br />
<br />
<div style = "overflow-x:auto; width:100%">
<asp:GridView ID="GridView1" runat="server" CssClass="mydatagrid" PagerStyle-CssClass="pager" HeaderStyle-CssClass="header"
RowStyle-CssClass="rows" EnableSortingAndPagingCallbacks="True" AutoGenerateEditButton="False" ShowHeaderWhenEmpty="True"
EnableViewState="true" AllowPaging="True" PageSize="5" OnPageIndexChanging="GridView1_PageIndexChanging">
</asp:GridView>
</div>
</div>
<asp:PlaceHolder ID="PlaceHolderFooter" runat="server"></asp:PlaceHolder>
</div>
</form>
</body>
</html>
ASPX.CS (code behind)
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
namespace DynamicStoreWebApplication
{
public partial class UDC : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
UserControl uc1 = (UserControl)Page.LoadControl("~/Header.ascx");
PlaceHolderHeader.Controls.Add(uc1);
UserControl uc2 = (UserControl)Page.LoadControl("~/Menu.ascx");
PlaceHolderMenu.Controls.Add(uc2);
UserControl uc3 = (UserControl)Page.LoadControl("~/Footer.ascx");
PlaceHolderFooter.Controls.Add(uc3);
DateTo.Text = DateTime.Today.ToString("yyyy-MM-dd");
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
BindGridView();
}
protected void BindGridView()
{
string conn = "";
conn = ConfigurationManager.ConnectionStrings["Connection"].ToString();
SqlConnection objsqlconn = new SqlConnection(conn);
try
{
objsqlconn.Open();
SqlCommand objcmd = new SqlCommand("DY_FindUdcList", objsqlconn);
objcmd.CommandType = CommandType.StoredProcedure;
SqlParameter RCp = objcmd.Parameters.Add("#RC", SqlDbType.Int);
RCp.Direction = ParameterDirection.ReturnValue;
SqlParameter DateFromp = objcmd.Parameters.Add("#DateFrom", SqlDbType.DateTime);
DateFromp.Value = DateFrom.Text;
SqlParameter DateTop = objcmd.Parameters.Add("#DateTo", SqlDbType.DateTime);
DateTop.Value = DateTo.Text;
SqlParameter UdcCelp = objcmd.Parameters.Add("#UdcCel", SqlDbType.Int);
UdcCelp.Value = -1;
SqlParameter TopResultsp = objcmd.Parameters.Add("#TopResults", SqlDbType.Bit);
if (TopResults.Checked)
{
TopResultsp.Value = 1;
}
else
{
TopResultsp.Value = 0;
}
SqlParameter Searchp = objcmd.Parameters.Add("#Search", SqlDbType.VarChar);
Searchp.Value = Search.Text;
SqlParameter Operp = objcmd.Parameters.Add("#Oper", SqlDbType.VarChar);
Operp.Value = "";
SqlParameter Termp = objcmd.Parameters.Add("#Term", SqlDbType.VarChar);
Termp.Value = "";
SqlParameter Errorep = objcmd.Parameters.Add("#Errore", SqlDbType.VarChar);
Errorep.Value = "";
Errorep.Direction = ParameterDirection.Output;
SqlDataAdapter adapter = new SqlDataAdapter(objcmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
objcmd.Dispose();
}
catch (Exception ex)
{
Response.Write(ex.Message.ToString());
}
finally
{
objsqlconn.Close();
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindGridView();
}
}
}
Your code should work but remove EnableSortingAndPagingCallbacks="True" from the gridview declaration and try it. I think you have not also allowed sorting..

I need to let the user edit and update the data in gridview so that database data gets updated

Here in my code i'm trying to let the user edit the gridview and hence update the database accordingly.The gridview is made on a webform page in aspx which shows the user data in tabular structure.But the problem is here that when i click on edit link of gridview it lets me to edit the data but when i update the gridview row,the associated event of onrowupdating doesn't gets called or fired at all.Even when i written all the code for it but still it's not working.What's the problem in this Please help me with this.Below is my whole code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication5.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
Welcome To My First Web Form<br />
<h1> Candidate Registration Form</h1>
<br />
<br />
Applicant's Name:
<asp:TextBox ID="TextBox1" runat="server" CausesValidation="True" EnableViewState="False" ValidateRequestMode="Enabled"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="Please enter Your Name!" ForeColor="Red"></asp:RequiredFieldValidator>
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Applicant's FName"></asp:Label>
:
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="TextBox2" ErrorMessage="Please enter your Father name!" ForeColor="Red"></asp:RequiredFieldValidator>
<br />
<br />
<asp:Label ID="Label3" runat="server" Text="Gender"></asp:Label>: <asp:RadioButtonList ID="gender" RepeatDirection="Horizontal" runat="server" Width="141px" RepeatLayout="Flow">
<asp:ListItem>Male</asp:ListItem>
<asp:ListItem>Female</asp:ListItem>
</asp:RadioButtonList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="gender" ErrorMessage="Please Choose your Gender" ForeColor="Red"></asp:RequiredFieldValidator>
<br />
<br />
<asp:Label ID="Label2" runat="server" Text="E-mail ID"></asp:Label>
:
<asp:TextBox ID="TextBox3" runat="server" OnTextChanged="TextBox3_TextChanged"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="TextBox3" Display="Dynamic" ErrorMessage="E-mail address is required">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="TextBox3" Display="Dynamic" ErrorMessage="E-mail addresses must be in the format of name#domain.xyz" ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*" ForeColor="Red">Invalid Format</asp:RegularExpressionValidator>
<br />
<br />
<asp:Label ID="Label4" runat="server" Text="password"></asp:Label>
:
<asp:TextBox ID="TextBox4" runat="server" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ControlToValidate="TextBox4" Display="Dynamic" ErrorMessage="Password is Required!" ForeColor="Red"></asp:RequiredFieldValidator>
<br />
<br />
<asp:Label ID="Label5" runat="server" Text="Confirm Password"></asp:Label>
:
<asp:TextBox ID="TextBox5" runat="server" TextMode="Password"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator1" runat="server" ControlToValidate="TextBox5" ErrorMessage="The passwords Didn't Match!" ForeColor="Red" ControlToCompare="TextBox4" Display="Dynamic"></asp:CompareValidator>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" />
<br />
<asp:GridView ID="GridView1" runat="server"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
AutoGenerateDeleteButton="True"
AutoGenerateEditButton="True"
OnRowEditing="GridView1_RowEditing"
OnRowUpdating="GridView1_RowUpdating1">
<%-- <Columns>
<asp:BoundField DataField="Cname" />
<asp:BoundField DataField="Cfname" />
<asp:BoundField DataField="Cmail" />
</Columns>--%>
</asp:GridView>
<br />
<br />
</div>
</form>
</body>
</html>
CS code file for this:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace WebApplication5
{
public partial class WebForm1 : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\admin\documents\visual studio 2013\Projects\WebApplication5\WebApplication5\App_Data\Candidates.mdf;Integrated Security=True");
public static int count = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
gvbind();
//DataTable dt = new DataTable();
//dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Name"), new DataColumn("FatherName"), new DataColumn("E-mail") });
//ViewState["Candidates"] = dt;
//GridView1.DataSource = (DataTable)ViewState["Candidates"];
//GridView1.DataBind();
}
}
protected void gvbind()
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Candidates", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
protected void TextBox3_TextChanged(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
count += 1;
int rowIndex = 0;
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Candidates values('"+TextBox1.Text+"','"+TextBox2.Text+"','"+TextBox3.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
//if (count > 1)
//{
// DataTable dtCurrentTable = (DataTable)ViewState["Candidates"];
// DataRow drCurrentRow = null;
// if (dtCurrentTable.Rows.Count > 0) {
// //for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
// //{
// drCurrentRow = dtCurrentTable.NewRow();
// int totalrows = dtCurrentTable.Rows.Count;
// dtCurrentTable.Rows.Add(drCurrentRow);
// dtCurrentTable.Rows[totalrows]["Name"] = TextBox1.Text;
// dtCurrentTable.Rows[totalrows]["FatherName"] = TextBox2.Text;
// dtCurrentTable.Rows[totalrows]["E-mail"] = TextBox3.Text;
// rowIndex++;
// //}
// ViewState["Candidates"] = dtCurrentTable;
// GridView1.DataSource = dtCurrentTable;
// GridView1.DataBind();
// TextBox1.Text = string.Empty;
// TextBox2.Text = string.Empty;
// TextBox3.Text = string.Empty;
// }
//}
//else
//{
// DataTable dt = (DataTable)ViewState["Candidates"];
// dt.Rows.Add(TextBox1.Text.Trim(), TextBox2.Text.Trim(), TextBox3.Text.Trim());
// ViewState["Candidates"] = dt;
// TextBox1.Text = string.Empty;
// TextBox2.Text = string.Empty;
// TextBox3.Text = string.Empty;
// BindGrid();
//}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
//protected void BindGrid()
//{
// //GridView1.DataSource = (DataTable)ViewState["Candidates"];
// //GridView1.DataBind();
//}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
gvbind();
}
protected void GridView1_RowUpdating1(object sender, GridViewUpdateEventArgs e)
{
string name = GridView1.SelectedRow.Cells[0].Text;
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label lblID = (Label)row.FindControl("lblID");
TextBox textName = (TextBox)row.Cells[0].Controls[0];
TextBox textFname = (TextBox)row.Cells[1].Controls[0];
TextBox texte = (TextBox)row.Cells[2].Controls[0];
////TextBox textadd = (TextBox)row.FindControl("txtadd");
////TextBox textc = (TextBox)row.FindControl("txtc");
GridView1.EditIndex = -1;
con.Open();
SqlCommand cmd = new SqlCommand("update Candidates set Cname='" + textName.Text + "',Cfname='" + textFname.Text + "',Cmail='" + texte.Text + "'where Cname='" + name + "'", con);
cmd.ExecuteNonQuery();
con.Close();
gvbind();
//GridView1.DataBind();
}
}
}

How to make the second table appears after selecting a row in the first table?

I am a new ASP.NET developer and trying to develop two dynamic tables where the user can add a new row directly in the first table, when he finished adding it, he will be able to select it to open the second table underneath the first table. I have a problem now in selecting on the rows in the first table in order to show the second table. So how to get it?
FYI, I have the following database design:
Quiz Table: QuizID, Title, Description
Question Table: QuestionID, Question, QuestionOrder, AnswerExplanation
QuestionImage Table: ID, QuestionID, URL
Answer Table: AnswerID, Answer
QuizContent Table: ID, QuizID, QuestionID, AnswerID
In addition, the first table will be for inserting the questions and the second table will be for inserting the answers. So how I can select a question to show the second table and being able to insert the answers for that question.
ASP.NET Code:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" ChildrenAsTriggers="true" UpdateMode="Conditional">
<ContentTemplate>
<asp:Table ID="questionsList" runat="server" Width="70%" CellPadding="0" CellSpacing="0"
style="border:2px solid #003366; font-size:17px; font-weight:bold;">
<asp:TableHeaderRow>
<asp:TableHeaderCell>ID</asp:TableHeaderCell>
<asp:TableHeaderCell>Question</asp:TableHeaderCell>
<asp:TableHeaderCell>Question Order</asp:TableHeaderCell>
<asp:TableHeaderCell>Answer Explanation</asp:TableHeaderCell>
</asp:TableHeaderRow>
</asp:Table>
<asp:Table ID="Table1" runat="server" Width="70%" CellPadding="5" CellSpacing="0"
style="border:2px solid #003366;">
<asp:TableFooterRow>
<asp:TableCell>Add</asp:TableCell>
<asp:TableCell >
<asp:TextBox ID="txtQuestion" runat="server"></asp:TextBox>
<%--For the txtQuestion TextBox Control--%>
<ajaxToolkit:TextBoxWatermarkExtender ID="TextBoxWatermarkExtender1" runat="server"
TargetControlID="txtQuestion" WatermarkText="Type the Question here"
WatermarkCssClass="watermarked">
</ajaxToolkit:TextBoxWatermarkExtender>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtQuestionOrder" runat="server"></asp:TextBox>
<%--For the txtQuestionOrder TextBox Control--%>
<ajaxToolkit:TextBoxWatermarkExtender ID="TextBoxWatermarkExtender2" runat="server"
TargetControlID="txtQuestionOrder" WatermarkText="Type the Question Order here"
WatermarkCssClass="watermarked">
</ajaxToolkit:TextBoxWatermarkExtender>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtAnswerExplanation" runat="server"></asp:TextBox>
<%--For the txtAnswerExplanation TextBox Control--%>
<ajaxToolkit:TextBoxWatermarkExtender ID="TextBoxWatermarkExtender3" runat="server"
TargetControlID="txtAnswerExplanation" WatermarkText="Type the Answer Explanation here"
WatermarkCssClass="watermarked">
</ajaxToolkit:TextBoxWatermarkExtender>
</asp:TableCell>
<asp:TableCell>
<span style="margin:3px 10px 0px 0px;">
<asp:ImageButton ID="addButton" runat="server" ImageUrl="Images/tick_small.png" OnClick="addQuestion" />
</span>
</asp:TableCell>
</asp:TableFooterRow>
</asp:Table>
</ContentTemplate>
</asp:UpdatePanel>
Code-Behind:
public void fill_Questions()
{
string connString = ConfigurationManager.ConnectionStrings["QuizSysDBConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
string selectQuery = "SELECT * FROM Question";
SqlCommand cmd = new SqlCommand(selectQuery, conn);
DataSet ds = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = cmd;
Table table = (Table)UpdatePanel1.FindControl("questionsList");
try
{
table.Rows.Clear();
//open the connection
conn.Open();
//filling the dataset with the data
sda.Fill(ds);
//close the connection
conn.Close();
}
catch
{
table.Rows.Clear();
}
//Loading the data into the table
if (ds.Tables.Count > 0)
{
int rowsNum = ds.Tables[0].Rows.Count;
for (int i = 0; i < rowsNum; i++)
{
TableRow row = new TableRow();
table.Rows.Add(row);
for (int colCount = 0; colCount < 5; colCount++)
{
TableCell cell = new TableCell();
row.Cells.Add(cell);
if (colCount == 0)
{
//int n = i + 1;
cell.Controls.Add(new LiteralControl(ds.Tables[0].Rows[i]["QuestionID"].ToString()));
}
else if (colCount == 1)
{
cell.Controls.Add(new LiteralControl(ds.Tables[0].Rows[i]["Question"].ToString()));
}
else if (colCount == 2)
{
cell.Controls.Add(new LiteralControl(ds.Tables[0].Rows[i]["QuestionOrder"].ToString()));
}
else if (colCount == 3)
{
cell.Controls.Add(new LiteralControl(ds.Tables[0].Rows[i]["AnswerExplanation"].ToString()));
}
else if (colCount == 4)
{
ImageButton deleteButton = new ImageButton();
deleteButton.ImageUrl = "Images/DeleteRed.png";
deleteButton.ID = ds.Tables[0].Rows[i]["QuestionID"].ToString() + "_" + i;
deleteButton.Click += new ImageClickEventHandler(deleteQuestion);
cell.Controls.Add(deleteButton);
}
} //End for loop
}//End OUTER for loop
}//End if statement
}
//For deleting question
public void deleteQuestion(object sender, EventArgs e)
{
string id = ((ImageButton)sender).ID.ToString().Split('_')[0];
try
{
string connString = ConfigurationManager.ConnectionStrings["QuizSysDBConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
string deleteQuery = "DELETE FROM Question WHERE QuestionID = #id";
SqlCommand cmd = new SqlCommand(deleteQuery,conn);
cmd.Parameters.AddWithValue("#id", id);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
fill_Questions();
}
catch(SqlException se){}
UpdatePanel1.Update();
}
//For adding questions
public void addQuestion(object sender, EventArgs e)
{
try
{
TextBox txtQuestion = (TextBox)UpdatePanel1.FindControl("txtQuestion");
TextBox txtQuestionOrder = (TextBox)UpdatePanel1.FindControl("txtQuestionOrder");
TextBox txtAnswerExplanation = (TextBox)UpdatePanel1.FindControl("txtAnswerExplanation");
string connString = ConfigurationManager.ConnectionStrings["QuizSysDBConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
string insertQuery = "INSERT INTO Question (Question, QuestionOrder, AnswerExplanation) VALUES (#Question, #QuestionOrder, #AnswerExplanation)";
SqlCommand cmd = new SqlCommand(insertQuery,conn);
cmd.Parameters.AddWithValue("#Question", txtQuestion.Text);
cmd.Parameters.AddWithValue("#QuestionOrder", txtQuestionOrder.Text);
cmd.Parameters.AddWithValue("#AnswerExplanation", txtAnswerExplanation.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
fill_Questions();
}
catch(SqlException se){}
}
UPDATE:
I created two tables for the Answers as I did for the questions. Now, How Am I gonna be able to show these table after selecting one question?
ASP.NET code:
<div align="center">
<h3>Answers List</h3>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" ChildrenAsTriggers="true" UpdateMode="Conditional">
<ContentTemplate>
<asp:Table ID="answersList" runat="server" Width="70%" CellPadding="0" CellSpacing="0"
style="border:2px solid #003366; font-size:17px; font-weight:bold;">
<asp:TableHeaderRow>
<asp:TableHeaderCell>Answer</asp:TableHeaderCell>
</asp:TableHeaderRow>
</asp:Table>
<asp:Table ID="Table2" runat="server" Width="70%" CellPadding="5" CellSpacing="0"
style="border:2px solid #003366;">
<asp:TableFooterRow>
<asp:TableCell>Add</asp:TableCell>
<asp:TableCell >
<asp:TextBox ID="txtAnswer" runat="server"></asp:TextBox>
<%--For the txtQuestion TextBox Control--%>
<ajaxToolkit:TextBoxWatermarkExtender ID="TextBoxWatermarkExtender4" runat="server"
TargetControlID="txtAnswer" WatermarkText="Type the Answer here"
WatermarkCssClass="watermarked">
</ajaxToolkit:TextBoxWatermarkExtender>
</asp:TableCell>
<asp:TableCell>
<asp:CheckBox ID="isCorrectCheckBox" runat="server" />
</asp:TableCell>
<asp:TableCell>
<span style="margin:3px 10px 0px 0px;">
<asp:ImageButton ID="ImageButton1" runat="server" ToolTip="Add" ImageUrl="Images/tick_small.png" OnClick="addAnswer" />
</span>
</asp:TableCell>
</asp:TableFooterRow>
</asp:Table>
</ContentTemplate>
</asp:UpdatePanel>
</div>

How to show the second table for inserting answers of the questions that have been inserted in the first table?

I am trying to develop two dynamic tables where the user can add a new row directly in the first table, when he finished adding it, he will be able to select it to open the second table underneath the first table. I have a probelm now in selecting on the rows in the first table in order to show the second table. So how to get it?
FYI, I have the following database design:
Quiz Table: QuizID, Title, Description
Question Table: QuestionID, Question, QuestionOrder, AnswerExplanation
QuestionImage Table: ID, QuestionID, URL
Answer Table: AnswerID, Answer
QuizContent Table: ID, QuizID, QuestionID, AnswerID
In addition, the first table will be for inserting the questions and the second table will be for inserting the answers. So how I can select a question to show the second table and being able to insert the answers for that question
ASP.NET Code:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" ChildrenAsTriggers="true" UpdateMode="Conditional">
<ContentTemplate>
<asp:Table ID="questionsList" runat="server" Width="70%" CellPadding="0" CellSpacing="0"
style="border:2px solid #003366; font-size:17px; font-weight:bold;">
<asp:TableHeaderRow>
<asp:TableHeaderCell>ID</asp:TableHeaderCell>
<asp:TableHeaderCell>Question</asp:TableHeaderCell>
<asp:TableHeaderCell>Question Order</asp:TableHeaderCell>
<asp:TableHeaderCell>Answer Explanation</asp:TableHeaderCell>
</asp:TableHeaderRow>
</asp:Table>
<asp:Table ID="Table1" runat="server" Width="70%" CellPadding="5" CellSpacing="0"
style="border:2px solid #003366;">
<asp:TableFooterRow>
<asp:TableCell>Add</asp:TableCell>
<asp:TableCell >
<asp:TextBox ID="txtQuestion" runat="server"></asp:TextBox>
<%--For the txtQuestion TextBox Control--%>
<ajaxToolkit:TextBoxWatermarkExtender ID="TextBoxWatermarkExtender1" runat="server"
TargetControlID="txtQuestion" WatermarkText="Type the Question here"
WatermarkCssClass="watermarked">
</ajaxToolkit:TextBoxWatermarkExtender>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtQuestionOrder" runat="server"></asp:TextBox>
<%--For the txtQuestionOrder TextBox Control--%>
<ajaxToolkit:TextBoxWatermarkExtender ID="TextBoxWatermarkExtender2" runat="server"
TargetControlID="txtQuestionOrder" WatermarkText="Type the Question Order here"
WatermarkCssClass="watermarked">
</ajaxToolkit:TextBoxWatermarkExtender>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtAnswerExplanation" runat="server"></asp:TextBox>
<%--For the txtAnswerExplanation TextBox Control--%>
<ajaxToolkit:TextBoxWatermarkExtender ID="TextBoxWatermarkExtender3" runat="server"
TargetControlID="txtAnswerExplanation" WatermarkText="Type the Answer Explanation here"
WatermarkCssClass="watermarked">
</ajaxToolkit:TextBoxWatermarkExtender>
</asp:TableCell>
<asp:TableCell>
<span style="margin:3px 10px 0px 0px;">
<asp:ImageButton ID="addButton" runat="server" ImageUrl="Images/tick_small.png" OnClick="addQuestion" />
</span>
</asp:TableCell>
</asp:TableFooterRow>
</asp:Table>
</ContentTemplate>
</asp:UpdatePanel>
Code-Behind:
public void fill_Questions()
{
string connString = ConfigurationManager.ConnectionStrings["QuizSysDBConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
string selectQuery = "SELECT * FROM Question";
SqlCommand cmd = new SqlCommand(selectQuery, conn);
DataSet ds = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = cmd;
Table table = (Table)UpdatePanel1.FindControl("questionsList");
try
{
table.Rows.Clear();
//open the connection
conn.Open();
//filling the dataset with the data
sda.Fill(ds);
//close the connection
conn.Close();
}
catch
{
table.Rows.Clear();
}
//Loading the data into the table
if (ds.Tables.Count > 0)
{
int rowsNum = ds.Tables[0].Rows.Count;
for (int i = 0; i < rowsNum; i++)
{
TableRow row = new TableRow();
table.Rows.Add(row);
for (int colCount = 0; colCount < 5; colCount++)
{
TableCell cell = new TableCell();
row.Cells.Add(cell);
if (colCount == 0)
{
//int n = i + 1;
cell.Controls.Add(new LiteralControl(ds.Tables[0].Rows[i]["QuestionID"].ToString()));
}
else if (colCount == 1)
{
cell.Controls.Add(new LiteralControl(ds.Tables[0].Rows[i]["Question"].ToString()));
}
else if (colCount == 2)
{
cell.Controls.Add(new LiteralControl(ds.Tables[0].Rows[i]["QuestionOrder"].ToString()));
}
else if (colCount == 3)
{
cell.Controls.Add(new LiteralControl(ds.Tables[0].Rows[i]["AnswerExplanation"].ToString()));
}
else if (colCount == 4)
{
ImageButton deleteButton = new ImageButton();
deleteButton.ImageUrl = "Images/DeleteRed.png";
deleteButton.ID = ds.Tables[0].Rows[i]["QuestionID"].ToString() + "_" + i;
deleteButton.Click += new ImageClickEventHandler(deleteQuestion);
cell.Controls.Add(deleteButton);
}
} //End for loop
}//End OUTER for loop
}//End if statement
}
//For deleting question
public void deleteQuestion(object sender, EventArgs e)
{
string id = ((ImageButton)sender).ID.ToString().Split('_')[0];
try
{
string connString = ConfigurationManager.ConnectionStrings["QuizSysDBConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
string deleteQuery = "DELETE FROM Question WHERE QuestionID = #id";
SqlCommand cmd = new SqlCommand(deleteQuery,conn);
cmd.Parameters.AddWithValue("#id", id);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
fill_Questions();
}
catch(SqlException se){}
UpdatePanel1.Update();
}
//For adding questions
public void addQuestion(object sender, EventArgs e)
{
try
{
TextBox txtQuestion = (TextBox)UpdatePanel1.FindControl("txtQuestion");
TextBox txtQuestionOrder = (TextBox)UpdatePanel1.FindControl("txtQuestionOrder");
TextBox txtAnswerExplanation = (TextBox)UpdatePanel1.FindControl("txtAnswerExplanation");
string connString = ConfigurationManager.ConnectionStrings["QuizSysDBConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
string insertQuery = "INSERT INTO Question (Question, QuestionOrder, AnswerExplanation) VALUES (#Question, #QuestionOrder, #AnswerExplanation)";
SqlCommand cmd = new SqlCommand(insertQuery,conn);
cmd.Parameters.AddWithValue("#Question", txtQuestion.Text);
cmd.Parameters.AddWithValue("#QuestionOrder", txtQuestionOrder.Text);
cmd.Parameters.AddWithValue("#AnswerExplanation", txtAnswerExplanation.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
fill_Questions();
}
catch(SqlException se){}
}
UPDATE:
I created two tables for the Answers as I did for the questions. Now, how am I gonna be able to show these table after selecting one question?
ASP.NET code:
<div align="center">
<h3>Answers List</h3>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" ChildrenAsTriggers="true" UpdateMode="Conditional">
<ContentTemplate>
<asp:Table ID="answersList" runat="server" Width="70%" CellPadding="0" CellSpacing="0"
style="border:2px solid #003366; font-size:17px; font-weight:bold;">
<asp:TableHeaderRow>
<asp:TableHeaderCell>Answer</asp:TableHeaderCell>
</asp:TableHeaderRow>
</asp:Table>
<asp:Table ID="Table2" runat="server" Width="70%" CellPadding="5" CellSpacing="0"
style="border:2px solid #003366;">
<asp:TableFooterRow>
<asp:TableCell>Add</asp:TableCell>
<asp:TableCell >
<asp:TextBox ID="txtAnswer" runat="server"></asp:TextBox>
<%--For the txtQuestion TextBox Control--%>
<ajaxToolkit:TextBoxWatermarkExtender ID="TextBoxWatermarkExtender4" runat="server"
TargetControlID="txtAnswer" WatermarkText="Type the Answer here"
WatermarkCssClass="watermarked">
</ajaxToolkit:TextBoxWatermarkExtender>
</asp:TableCell>
<asp:TableCell>
<asp:CheckBox ID="isCorrectCheckBox" runat="server" />
</asp:TableCell>
<asp:TableCell>
<span style="margin:3px 10px 0px 0px;">
<asp:ImageButton ID="ImageButton1" runat="server" ToolTip="Add" ImageUrl="Images/tick_small.png" OnClick="addAnswer" />
</span>
</asp:TableCell>
</asp:TableFooterRow>
</asp:Table>
</ContentTemplate>
</asp:UpdatePanel>
</div>

UpdatePanel Question

I have a dropdown menu bounded with values from the db on form load. I wanted to use the dropdown as a filter to update a datagrid using an updatepanel, which I managed to get working. I'm binding the datagrid in form load and on selected index changed as shown. I also want to use the same dropdown to update a formview using the DataValueField, which for some reason isn't working. Could the reason be that I'm using two different updatepanels and the same asynchpostbacktrigger? Where should I be binding data to the formview? Your input would be greatly appreciated! Thanks in advance...
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
conn.Open();
SqlCommand cmd3 = new SqlCommand("SELECT c.Email As CompanyEmail, c.Telephone AS Telephone, m.Email AS AdminEmail, m.FirstName + ' ' + m.LastName AS CompanyAdmin FROM Company c, Member m WHERE m.CompanyID = c.CompanyID AND m.CompanyID = '" + company_id + "' AND m.CompanyRole = 'Admin'", conn);
SqlCommand cmd = new SqlCommand("SELECT CompanyName, CompanyID FROM Company ORDER BY CompanyName", conn);
SqlCommand cmd2 = new SqlCommand("SELECT p.ProjectName AS ProjectName, p.ProjectID, p.CompanyID, p.Status AS Status FROM Project p, Company c WHERE p.CompanyID = c.CompanyID AND c.CompanyID = '" + company_id + "' ORDER BY ProjectName", conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (!Page.IsPostBack)
{
company_list.DataSource = ds;
company_list.DataTextField = "CompanyName";
company_list.DataValueField = "CompanyID";
company_list.DataBind();
company_list.Items.Insert(0, new System.Web.UI.WebControls.ListItem("-- Please Select Company --"));
}
//cmd2.Connection.Open();
cmd2.CommandType = CommandType.Text;
SqlDataAdapter sqlAdapter = new SqlDataAdapter(cmd2);
DataSet ds2 = new DataSet();
sqlAdapter.Fill(ds2);
Gridview1.DataSource = ds2;
Gridview1.DataBind();
FormView1.DataSource = cmd3.ExecuteReader();
FormView1.DataBind();
conn.Close();
//}
//cmd2.Connection.Close();
//cmd2.Connection.Dispose();
}
}
protected void company_list_SelectedIndexChanged(object sender, EventArgs e)
{
company_id = company_list.SelectedValue;
SqlConnection conn = new SqlConnection(GetConnectionString());
conn.Open();
SqlCommand cmd2 = new SqlCommand("SELECT p.ProjectName AS ProjectName, p.ProjectID, p.CompanyID, p.Status AS Status FROM Project p, Company c WHERE p.CompanyID = c.CompanyID AND c.CompanyID = '" + company_id + "' ORDER BY ProjectName", conn);
cmd2.CommandType = CommandType.Text;
SqlDataAdapter sqlAdapter = new SqlDataAdapter(cmd2);
DataSet ds2 = new DataSet();
sqlAdapter.Fill(ds2);
Gridview1.DataSource = ds2;
Gridview1.DataBind();
SqlCommand cmd = new SqlCommand("SELECT c.Email As CompanyEmail, c.Telephone AS Telephone, m.Email AS AdminEmail, m.FirstName + ' ' + m.LastName AS CompanyAdmin FROM Company c, Member m WHERE m.CompanyID = c.CompanyID AND m.CompanyID = '" + company_id + "' AND m.CompanyRole = 'Admin'", conn);
cmd.CommandType = CommandType.Text;
FormView1.DataSource = cmd.ExecuteReader();
FormView1.DataBind();
conn.Close();
}
ASP.NET:
<div style="float:left;">
<table>
<tr>
<td class="style1">Select Company:</td>
<td><asp:DropDownList ID="company_list" runat="server"
onselectedindexchanged="company_list_SelectedIndexChanged" width="185" AutoPostBack="true" /></td>
</tr>
<tr>
<td colspan="2" align="right"> </td>
</tr>
</table>
<asp:UpdatePanel ID="UpdateInfo" runat="server">
<ContentTemplate>
<asp:FormView ID="FormView1" runat="server">
<ItemTemplate>
<table>
<tr>
<td>Company Admin:</td>
<td><asp:TextBox Text='<%# Eval("Email") %>' CssClass="input input1" ID="co_admin" width="150" runat="server" ReadOnly="True" /></td>
</tr>
<tr>
<td>Admin Email:</td>
<td><asp:TextBox Text='<%# Eval("AdminEmail") %>' CssClass="input input1" ID="ad_email" width="150" runat="server" ReadOnly="True" /></td>
</tr>
<tr>
<td>Company Email:</td>
<td><asp:TextBox Text='<%# Eval("CompanyEmail") %>' CssClass="input input1" ID="co_email" width="150" runat="server" ReadOnly="True" /></td>
</tr>
<tr>
<td>Telephone:</td>
<td><asp:TextBox Text='<%# Eval("Telephone") %>' CssClass="input input1" ID="telephone" width="150" runat="server" ReadOnly="True" /></td>
</tr>
<tr>
<td></td>
<td><asp:Button CssClass="button_style" width="170" ID="export" Text="EXPORT TO EXCEL" runat="server" /></td>
</tr>
</table>
</ItemTemplate>
</asp:FormView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="company_list" />
</Triggers>
</asp:UpdatePanel>
</div>
<center>
<asp:UpdatePanel ID="UpdateGrid" runat="server">
<ContentTemplate>
<asp:gridview ID="Gridview1" runat="server" ShowFooter="True"
AutoGenerateColumns="False" GridLines="None">
<Columns>
<asp:TemplateField HeaderText="Project Name">
<ItemTemplate>
<asp:TextBox Text='<%# Eval("ProjectName") %>' CssClass="input input1" ID="project_name" width="150" runat="server" ReadOnly="True"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<ItemStyle Width="150" />
<ItemTemplate>
<center><asp:Image ImageUrl='<%# GetStatusImage(Eval("Status").ToString()) %>' ID="status" runat="server"/></center>
</ItemTemplate>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="company_list" />
</Triggers>
</asp:UpdatePanel>
I tried to recreate your scenario with this following code. (And it works)
protected void Page_Load(object sender, EventArgs e)
{
var foos = GetFoos();
Gridview1.DataSource = foos;
Gridview1.DataBind();
DetailsView1.DataSource = foos;
DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);
DetailsView1.DataBind();
DropDownList1.Items.AddRange(foos.Select(f => new ListItem(f.Name, f.Name)).ToArray());
DropDownList1.Items.Insert(0,new ListItem("-Select-"));
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
var selectedValue = DropDownList1.SelectedValue;
var foos = GetFoos().Where(f => f.Name == selectedValue);
Gridview1.DataSource = foos;
Gridview1.DataBind();
DetailsView1.DataSource = foos;
DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);
DetailsView1.DataBind();
}
static List<Foo> GetFoos()
{
var list = new List<Foo>();
for(int i=0;i<10;i++)
{
list.Add(new Foo {City = "City" + i, Name = "Name" + i});
}
return list;
}
class Foo
{
public string Name { get; set; }
public string City { get; set; }
}
and here's the markup
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView runat="server" ID="Gridview1">
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="DropDownList1" />
</Triggers>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="125px">
</asp:DetailsView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="DropDownList1" />
</Triggers>
</asp:UpdatePanel>
</asp:Content>
So, it's something with the formview you have. Can you switch to using DetailsView ?

Categories

Resources