I have a details view and a button, and when I click on the button, I want to check if the username is already in the database or not. I tried the below code but it goes to the else statement, even if the username exists.
Any help?
protected void Button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
string query = "select Username from [Login]";
SqlCommand cmd = new SqlCommand(query);
SqlDataAdapter sqlda = new SqlDataAdapter(cmd.CommandText, con);
DataTable dt = new DataTable();
sqlda.Fill(dt);
int RowCount = dt.Rows.Count;
for (int i = 0; i < RowCount; i++)
{
Label13.Text = ((TextBox)DetailsView1.FindControl("TextBox1")).Text;
Label14.Text = dt.Rows[i]["Username"].ToString();
if (Label13.Text == Label14.Text)
{
string message = "Username is Already Exists";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script type = 'text/javascript'>");
sb.Append("window.onload=function(){");
sb.Append("alert('");
sb.Append(message);
sb.Append("')};");
sb.Append("</script>");
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());
}
else
{
string message = "Successfully saved";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script type = 'text/javascript'>");
sb.Append("window.onload=function(){");
sb.Append("alert('");
sb.Append(message);
sb.Append("')};");
sb.Append("</script>");
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());
}
}
}
Details view markup:
<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False"
CellPadding="4" DataKeyNames="Username" DataSourceID="SqlDataSource3"
ForeColor="#333333" GridLines="None" Height="50px" Width="283px"
style="margin-top: 0px; text-align: left;"
onitemupdated="DetailsView1_ItemUpdated" onitemdeleted="DetailsView1_ItemDeleted"
oniteminserted="DetailsView1_ItemInserted" DefaultMode="Insert"
oniteminserting="DetailsView1_ItemInserting">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<CommandRowStyle BackColor="#E2DED6" Font-Bold="True" />
<EditRowStyle BackColor="#999999" />
<FieldHeaderStyle BackColor="#E9ECF1" Font-Bold="True" />
<Fields>
<asp:TemplateField HeaderText="Username" SortExpression="Username">
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Username") %>'></asp:Label>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Username") %>'
ValidationGroup="1"></asp:TextBox>
<asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server"
ErrorMessage="*" ControlToValidate="TextBox1" ForeColor="Red"
ValidationGroup="1"></asp:RequiredFieldValidator>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Username") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Password" SortExpression="Password">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Password") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Password") %>' ValidationGroup="1"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ControlToValidate="TextBox2" ErrorMessage="*" ForeColor="Red"
ValidationGroup="1"></asp:RequiredFieldValidator>
</InsertItemTemplate>
<ItemTemplate>
</ItemTemplate>
<ControlStyle />
</asp:TemplateField>
<asp:TemplateField HeaderText="UserType" SortExpression="UserType">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("UserType") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:DropDownList ID="DropDownList4" runat="server"
ConnectionString ="<%$ConnectionStrings: ConnectionString %>"
SelectedValue='<%# Bind("UserType") %>' ValidationGroup="1">
<asp:ListItem>--Select--</asp:ListItem>
<asp:ListItem>employee</asp:ListItem>
<asp:ListItem>doctor</asp:ListItem>
<asp:ListItem>student</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
ControlToValidate="DropDownList4" ErrorMessage="*" ForeColor="Red"
InitialValue="--Select--" ValidationGroup="1"></asp:RequiredFieldValidator>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("UserType") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Button" ShowInsertButton="True" ValidationGroup="1" />
</Fields>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
</asp:DetailsView>
Why don't you pass username as parameter to Db.
string query = "select Username from [Login] where Username=#username";
var nameParam = new SqlParameter("username");
nameParam.Value = Label13.Text;
cmd.Parameters.Add(nameParam);
It will fetch only records if username will exist in db.
Then Check it using rowCount.
if(RowCount> 0){
//Username exist
}else {
//Do other work
}
Can you please try this way.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
string query = "select Username from [Login] WHERE Username='"+((TextBox)DetailsView1.FindControl("TextBox1")).Text+"'";
SqlCommand cmd = new SqlCommand(query);
SqlDataReader reader = cmd.ExecuteReader();
if(reader.HasRows())
{
// The username exist
}
Related
I have a grid view control in my page that indexes all the Lecture Contents. I have added a Text Box control and a Link Button. But for the Lectures that have no Content yet, the Grid View does not appear.
Have tried many references, as a result the footer has appeared but I am not able to insert data using the Controls in the footer.
My main objective is to make the Controls behave same in both scenarios.
Here is the Grid View Code.
`<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" EmptyDataText="No Contents found for this lecture." ShowFooter="true" HeaderStyle-Wrap="false" Width="70%" CssClass="Grid" AlternatingRowStyle-CssClass="alt" PagerStyle-CssClass="pgr" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText=" LectureID " SortExpression="lecc_id">
<ItemTemplate>
<asp:Label ID="lbllecc_id" runat="server" Text='<%# Bind("lecc_id") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lbllecc_id" runat="server" T`enter code here`ext="Create New">
</asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=" Content " SortExpression="lecc_contents">
<EditItemTemplate>
<asp:TextBox ID="tblecc_contents" runat="server" Text='<%# Bind("lecc_contents") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbllecc_contents" runat="server" Text='<%# Bind("lecc_contents") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtcontent" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfcontent" runat="server" ErrorMessage="Content field cannot be blank." ControlToValidate="txtcontent" Text="*" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:LinkButton ID="createcontent" runat="server" OnClick="createcontent" CssClass="btn-sm btn-default">Insert Content</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</EmptyDataTemplate>
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" Font-Size="17px" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#F7F7DE" Font-Bold="False" Font-Size="14px" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FBFBF2" />
<SortedAscendingHeaderStyle BackColor="#848384" />
<SortedDescendingCellStyle BackColor="#EAEAD3" />
<SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>`
and the code behind functions for grid view.
`protected void Page_Load(object sender, EventArgs e){
if (Session["fac_username"] != null)
{
String username = Convert.ToString(Session["fac_username"]);
if (!IsPostBack)
{
BindGridViewData();
}
}
else
{
Response.Redirect("~/Account/Login.aspx");
}
}protected void BindGridViewData(){
int lecID = Convert.ToInt32(Session["lecID"]);
GridView1.DataSource = DataAccessLayer.getAllContents(lecID);
GridView1.DataBind();} protected void GridView1_SelectedIndexChanged(object sender, EventArgs e){
}
protected void createcontent(object sender, EventArgs e){
int lecID = Convert.ToInt32(Session["lecID"]);
con.Open();
SqlCommand command = new SqlCommand("insert into uni_lect_content(lecc_id, lecc_contents) values(#lecc_id, #lecc_contents)", con);
command.Parameters.AddWithValue("#lecc_id", lecID);
command.Parameters.AddWithValue("#lecc_contents", ((TextBox)GridView1.FooterRow.FindControl("txtcontent")).Text);
command.ExecuteNonQuery();
con.Close();
lblmsg.Text = "New Course Successfully Created..!";}`
DataAccessLayer class's getAllConents() method is here.
`public class AllContents
{
public long lecc_id { get; set; }
public string lecc_contents { get; set; }
}
public class DataAccessLayer
{
public static List<AllContents> getAllContents( int lecID){
List<AllContents> listAll = new List<AllContents>();
string cs = ConfigurationManager.ConnectionStrings["ILMSConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand com = new SqlCommand("select lecc_id, lecc_contents from uni_lect_content, uni_lectures, uni_offered_courses where uni_lect_content.lecc_id = uni_lectures.lec_id and uni_lectures.cours_offer_id = uni_offered_courses.cours_offer_id and lecc_id = '"+lecID+"'", con);
con.Open();
SqlDataReader rdr = com.ExecuteReader();
while (rdr.Read())
{
AllContents obj = new AllContents();
obj.lecc_id = Convert.ToInt32(rdr["lecc_id"]);
obj.lecc_contents = rdr["lecc_contents"].ToString();
listAll.Add(obj);
}
}
return listAll;
}`
Help me out of this situation.
Thanks in advance.
FRONT END GRDIVIEW
<asp:GridView ID="grdview" ShowFooter="true" OnRowEditing="grdview_RowEditing" OnRowCancelingEdit="grdview_RowCancelingEdit" OnRowCommand="grdview_RowCommand" OnRowUpdating="grdview_RowUpdating" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="SR No.">
<ItemTemplate>
<%#Container.DataItemIndex+1 %>
<asp:Label ID="lblid" runat="server" Text='<%#Eval("Id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" HeaderText="Emp Name">
<ItemTemplate>
<asp:Label ID="elblempname" runat="server" Text='<%#Eval("EmpName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="etxtempname" runat="server" Text='<%#Eval("EmpName") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ftxtempname" runat="server" ></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" HeaderText="Emp No">
<ItemTemplate>
<asp:Label ID="elblempno" runat="server" Text='<%#Eval("EmpNo") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="etxtempno" runat="server" Text='<%#Eval("EmpNo") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ftxtempno" runat="server" ></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" HeaderText="Email">
<ItemTemplate>
<asp:Label ID="elblempemail" runat="server" Text='<%#Eval("Email_Id") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="etxtempemail" runat="server" Text='<%#Eval("Email_Id") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ftxtempemail" runat="server" ></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" HeaderText="Age">
<ItemTemplate>
<asp:Label ID="elblempage" runat="server" Text='<%#Eval("Age") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="etxtempage" runat="server" Text='<%#Eval("Age") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ftxtempage" runat="server" ></asp:TextBox>
<asp:Button ID="btnAdd" CommandName="AddNew" runat="server" Text="Add" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
BACKEND CODE
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
grdview.DataSource = ds;
grdview.DataBind();
int columncount = grdview.Rows[0].Cells.Count;
grdview.Rows[0].Cells.Clear();
grdview.Rows[0].Cells.Add(new TableCell());
grdview.Rows[0].Cells[0].ColumnSpan = columncount;
grdview.Rows[0].Cells[0].Text = "No Records Found";
if (e.CommandName == "AddNew")
{
TextBox ftxtempname = (TextBox)grdview.FooterRow.FindControl("ftxtempname");
TextBox ftxtempno = (TextBox)grdview.FooterRow.FindControl("ftxtempno");
TextBox ftxtempemail = (TextBox)grdview.FooterRow.FindControl("ftxtempemail");
TextBox ftxtempage = (TextBox)grdview.FooterRow.FindControl("ftxtempage");
using (con)
{
SqlCommand cmd = new SqlCommand("usp_add_upd_emptb", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EmpName", ftxtempname.Text);
cmd.Parameters.AddWithValue("#EmpNo", ftxtempno.Text);
cmd.Parameters.AddWithValue("#Desig", ftxtempage.Text);
cmd.Parameters.AddWithValue("#Email", ftxtempemail.Text);
con.Open();
cmd.ExecuteNonQuery();
}
This is a working complete code.
I am trying to populate a drop down list in the footer row of a grid view. my mark up is as follows:
<asp:Label ID="lblGrdImages" runat="server" ></asp:Label>
<asp:GridView
ID="grdImages"
runat="server"
AllowPaging="true"
ShowFooter="true"
PageSize="5"
AutoGenerateColumns="false"
OnPageIndexChanging="grdImages_PageIndexChanging"
OnRowCancelingEdit="grdImages_RowCancelingEdit"
OnRowCommand="grdImages_RowCommand"
OnRowEditing="grdImages_RowEditing"
OnRowUpdating="grdImages_RowUpdating"
OnRowDeleting="grdImages_RowDeleting"
EmptyDataText="No Data Available at this Time" >
<AlternatingRowStyle BackColor="White" ForeColor="#284775"></AlternatingRowStyle>
<Columns>
<asp:TemplateField AccessibleHeaderText="Product ID" HeaderText="Product ID" FooterText="Product ID">
<ItemTemplate>
<asp:Label ID="lblProdId" runat="server" Text='<%# Eval("pi.ProductId") %>' ></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblEditProdId" runat="server" Text='<%# Eval("pi.ProductId") %>' ></asp:Label>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="lstAddProdId" runat="server" AppendDataBoundItems="true" >
<asp:ListItem>Select a product</asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Product Main Image" FooterText="Product Main Image" HeaderText="Product Main Image">
<ItemTemplate>
<asp:Label ID="lblMainImgId" runat="server" Text='<%# Eval("pi.ImageId") %>' ></asp:Label>
<asp:Image ID="imgMain" runat="server" Height="250" Width="250" ImageUrl='<%# Eval("pi.ImagePath") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:FileUpload ID="flupMain" runat="server" AllowMultiple="false" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Supporting Images" FooterText="Supporting Images" HeaderText="Supporting Images">
<ItemTemplate>
<h2>repeater here</h2>
</ItemTemplate>
<FooterTemplate>
<asp:FileUpload ID="flupExtra" runat="server" AllowMultiple="true" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:LinkButton ID="btnEdit" Text="Edit" runat="server" CommandName="Edit" />
<br />
<span onclick="return confirm('Are you sure you want to declare this product Discontinued?')">
<asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CommandName="Delete" />
</span>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
<br />
<asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAddRecord" runat="server" Text="Add" CommandName="Add"></asp:Button>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999"></EditRowStyle>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></FooterStyle>
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></HeaderStyle>
<PagerStyle HorizontalAlign="Center" BackColor="#284775" ForeColor="White"></PagerStyle>
<RowStyle BackColor="#F7F6F3" ForeColor="#333333"></RowStyle>
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333"></SelectedRowStyle>
<SortedAscendingCellStyle BackColor="#E9E7E2"></SortedAscendingCellStyle>
<SortedAscendingHeaderStyle BackColor="#506C8C"></SortedAscendingHeaderStyle>
<SortedDescendingCellStyle BackColor="#FFFDF8"></SortedDescendingCellStyle>
<SortedDescendingHeaderStyle BackColor="#6F8DAE"></SortedDescendingHeaderStyle>
</asp:GridView>
My code behind function to populate the drop down list:
protected void lstProducts()
{
// find dropdownlist in the footer row of the gridview
DropDownList prods = (DropDownList)grdImages.FooterRow.FindControl("lstAddProdId");
// define ado.net objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader reader;
// define the sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "LstProds";
try
{
con.Open(); // try to connect to db.
reader = cmd.ExecuteReader(); // execut the reader
while (reader.Read())
{
ListItem item = new ListItem(); // create listitem
item.Text = reader["p.ProductName"].ToString(); // add product name to item text
item.Value = reader["p.ProductId"].ToString(); // add productId to item value
prods.Items.Add(item); // populate dropdown list.
}
}
catch (Exception err)
{
lblGrdImages.Text = err.Message; // display error message in a label
}
finally
{
con.Close(); // close the connection.
}
}
When I try to run it I get the following error:
An exception of type 'System.NullReferenceException' occurred in App_Web_su5rfbqf.dll but was not handled in user code
I am unsure as to why I am getting this exception. I am assuming it is not able to find the control in the grid view footer row but I do not know why. It may be a silly mistake somewhere but I cannot figure out what I should do
EDIT I am getting the error on this line of lstProducts():
DropDownList prods = (DropDownList)grdImages.FooterRow.FindControl("lstAddProdId");
You have to set Datasource to your gridView first.The error you are getting is at grdImages.FooterRow=null.Try populating the grdImages first and then try to access it.
Here is a similar example that does the same
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"
runat="server" AutoGenerateColumns="false" ShowFooter = "true" OnDataBound = "OnDataBound">
<Columns>
<asp:TemplateField HeaderText = "Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtName" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Country">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("Country") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlCountries" runat="server">
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
</Columns>
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("Country") });
dt.Rows.Add(1, "John Hammond", "United States");
dt.Rows.Add(2, "Mudassar Khan", "India");
dt.Rows.Add(3, "Suzanne Mathews", "France");
dt.Rows.Add(4, "Robert Schidner", "Russia");
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void OnDataBound(object sender, EventArgs e)
{
DropDownList ddlCountries = GridView1.FooterRow.FindControl("ddlCountries") as DropDownList;
}
all my commands are working properly but the problem is
after I execute my Search command then I click the select link button on my GridView, My Gridview is refreshing and select the first row in the grid view and not the one that I searched.. example: first I run the Index Page then the GridView get all the record from database(10 populated record) and show to the index.. (No Problem)
then I type the firstname of the user to search it then i click the search button then the it filtered and show to gridview again here's the image
then I click the "Select" link button from Gridview and this what happened
that's what happened .. I clicked the select link button on "marcy's record" then it refreshed and get the value of RASI's Record on the first row...
but when my click select without searching it worked just fine
here's my code for search button
string strconn;
strconn = "select * from User_TBL_DB where (Firstname like '%'+#search+'%' and Middlename like '%'+#search2+'%' and Lastname like '%'+#search3+'%')";
SqlCommand xp = new SqlCommand(strconn, conn);
xp.Parameters.Add("#search", SqlDbType.NVarChar).Value = firstname_search.Text;
xp.Parameters.Add("#search2", SqlDbType.NVarChar).Value = middlename_search.Text;
xp.Parameters.Add("#search3", SqlDbType.NVarChar).Value = lastname_search.Text;
conn.Open();
xp.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = xp;
DataSet ds = new DataSet();
da.Fill(ds, "Name");
GridView1.DataSource = ds;
GridView1.DataBind();
conn.Close();
and here's my code for select link button on gridview
row = GridView1.SelectedRow;
firstname_tb.Text = (row.FindControl("lbl_Firstname") as Label).Text;
middlename_tb.Text = (row.FindControl("lbl_Middlename") as Label).Text;
lastname_tb.Text = (row.FindControl("lbl_Lastname") as Label).Text;
age_tb.Text = (row.FindControl("lbl_Age") as Label).Text;
id_tb.Text = (row.FindControl("lbl_ID") as Label).Text;
string gender = (row.FindControl("lbl_Sex") as Label).Text;
if (gender == "FEMALE")
{
female_rb.Checked = true;
male_rb.Checked = false;
}
else
{
male_rb.Checked = true;
female_rb.Checked = false;
}
and here's my codes for ASP on Gridview
<asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#3366CC"
BorderStyle="None" BorderWidth="1px" CellPadding="4" AutoGenerateColumns="False"
onselectedindexchanged="GridView1_SelectedIndexChanged" Width="581px"
onrowcommand="GridView1_RowCommand"
onselectedindexchanging="GridView1_SelectedIndexChanging">
<Columns>
<%--<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="Select_button" CommandArgument ='<%# Eval("ID") %>' CommandName="SelectRow" ForeColor="#8C4510" runat="server">Select</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>--%>
<asp:CommandField ShowSelectButton="True"></asp:CommandField>
<asp:TemplateField HeaderText="Firstname" SortExpression="Firstname">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Firstname") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbl_Firstname" runat="server" Text='<%# Bind("Firstname") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Middlename" SortExpression="Middlename">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Middlename") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbl_Middlename" runat="server" Text='<%# Bind("Middlename") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Lastname" SortExpression="Lastname">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("Lastname") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbl_Lastname" runat="server" Text='<%# Bind("Lastname") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age" SortExpression="Age">
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("Age") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbl_Age" runat="server" Text='<%# Bind("Age") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sex" SortExpression="Sex">
<EditItemTemplate>
<asp:TextBox ID="TextBox5" runat="server" Text='<%# Bind("Sex") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbl_Sex" runat="server" Text='<%# Bind("Sex") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID" SortExpression="ID">
<EditItemTemplate>
<asp:TextBox ID="TextBox6" runat="server" Text='<%# Bind("ID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbl_ID" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<HeaderStyle BackColor="#003399" Font-Bold="True"
ForeColor="#CCCCFF" />
<PagerStyle BackColor="#99CCCC" ForeColor="#003399"
HorizontalAlign="Left" />
<RowStyle BackColor="White" ForeColor="#003399" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True"
ForeColor="#CCFF99" />
<SortedAscendingCellStyle BackColor="#EDF6F6" />
<SortedAscendingHeaderStyle BackColor="#0D4AC4" />
<SortedDescendingCellStyle BackColor="#D6DFDF" />
<SortedDescendingHeaderStyle BackColor="#002876" />
</asp:GridView>
i connect it to sqlDatasource1 and disconnect it and leave the code as is. I used Showselectbutton="true"
that's my Problem hope you can help me thank you very much
I am creating exam website in vs2010 with asp.net C# 4.0,
in which I have the detailsview in questions page
<asp:DetailsView ID="questiondetail" runat="server" AutoGenerateRows="False"
BackColor="White" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px"
CellPadding="3" DataSourceID="SqlDataSource1" GridLines="Horizontal"
Height="69px" Width="100%">
<AlternatingRowStyle BackColor="#F7F7F7" />
<EditRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
<Fields>
<asp:TemplateField HeaderText="Question" SortExpression="question">
<EditItemTemplate>
<asp:TextBox ID="TextBox5" runat="server" Text='<%# Bind("question") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("question") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("question") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle Width="5px" />
<ItemStyle HorizontalAlign="Left" />
</asp:TemplateField>
<asp:TemplateField HeaderText="A)" SortExpression="a">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("a") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox5" runat="server" Text='<%# Bind("a") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:RadioButton ID="RadioButton1" runat="server" GroupName="ans"
Text='<%# Eval("a") %>' />
</ItemTemplate>
<HeaderStyle HorizontalAlign="Right" />
<ItemStyle HorizontalAlign="Left" />
</asp:TemplateField>
<asp:TemplateField HeaderText="B)" SortExpression="b">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("b") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox6" runat="server" Text='<%# Bind("b") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:RadioButton ID="RadioButton2" runat="server" GroupName="ans"
Text='<%# Eval("b") %>' />
</ItemTemplate>
<HeaderStyle HorizontalAlign="Right" />
<ItemStyle HorizontalAlign="Left" />
</asp:TemplateField>
<asp:TemplateField HeaderText="C)" SortExpression="c">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("c") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox7" runat="server" Text='<%# Bind("c") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:RadioButton ID="RadioButton3" runat="server" GroupName="ans"
Text='<%# Eval("c") %>' />
</ItemTemplate>
<HeaderStyle HorizontalAlign="Right" />
</asp:TemplateField>
<asp:TemplateField HeaderText="D)" SortExpression="d">
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("d") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox8" runat="server" Text='<%# Bind("d") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:RadioButton ID="RadioButton4" runat="server" GroupName="ans"
Text='<%# Eval("d") %>' />
</ItemTemplate>
<HeaderStyle HorizontalAlign="Right" />
</asp:TemplateField>
<asp:BoundField DataField="correctans" HeaderText="correctans"
SortExpression="correctans" Visible="False" />
</Fields>
<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
<PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
<RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
</asp:DetailsView>
code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
questiondetail.DataBind();
}
}
string userans = "Not selected";
protected void btnnext_Click(object sender, EventArgs e)
{
try
{
questiondetail.DataBind();
DataRowView dr = (DataRowView)questiondetail.DataItem;
// Create Answer object to save values
Answer a = new Answer();
a.QuestionID = questiondetail.PageIndex.ToString();
a.CorrectAnswer = dr.Row["correctans"].ToString();
//get user ans
questiondetail.DefaultMode = DetailsViewMode.Insert;
RadioButton r1 = questiondetail.FindControl("RadioButton1") as RadioButton;
RadioButton r2 = questiondetail.FindControl("RadioButton2") as RadioButton;
RadioButton r3 = questiondetail.FindControl("RadioButton3") as RadioButton;
RadioButton r4 = questiondetail.FindControl("RadioButton4") as RadioButton;
if (r1.Checked)
{
userans = "A";
}
else if (r2.Checked)
{
userans = "B";
}
else if (r3.Checked)
{
userans = "C";
}
else if (r4.Checked)
{
userans = "D";
}
else
{
userans = "Not selected";
}
questiondetail.DefaultMode = DetailsViewMode.ReadOnly;
a.UserAnswer = userans;
ArrayList al = (ArrayList)Session["AnswerList"];
al.Add(a);
Session.Add("AnswerList", al);
}
catch (Exception ex)
{
lblcatch.Text = ex.Message;
}
if (questiondetail.PageIndex == questiondetail.PageCount - 1)
{
Response.Redirect("Result.aspx");
}
else
{
questiondetail.PageIndex++;
}
if (questiondetail.PageIndex == questiondetail.PageCount - 1)
{
btnnext.Text = "Finish";
}
}
the problem is that on result page it shows every answer is Not selected
so how get that which radiobutton is checked in detailsview
Try to remove the questiondetail.DefaultMode = DetailsViewMode.Insert; and questiondetail.DefaultMode = DetailsViewMode.ReadOnly;
values of selected items in dropdownlist(edit gridview) are returning NULL. It should return selected values..
Code in aspx.cs file::
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
DropDownList ct = (DropDownList)row.FindControl("DropDownList6");
string ctype = ct.SelectedItem.Text;
string sql1 = ("Select Case_Type_Value FROM Case_Type where Case_Type_Text ='" + ctype + "' ");
DropDownList cs = (DropDownList)row.FindControl("DropDownList3");
string cstatus = cs.SelectedItem.Text;
string sql2 = ("Select Case_Status_Value FROM Case_Status where Case_Status_Text ='" + cstatus + "' ");
SqlConnection con= new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ToString());
SqlCommand cmd1 = new SqlCommand(sql1, con);
SqlCommand cmd2 = new SqlCommand(sql2, con);
con.Open();
int v1 = Convert.ToInt32(cmd1.ExecuteScalar());
int v2 = Convert.ToInt32(cmd2.ExecuteScalar());
con.Close();
SqlCommand cmd = new SqlCommand("UPDATE Table SET Case_Type = #Case_Type, Case_Status = #Case_Status, con);
cmd.Parameters.AddWithValue("#Case_Type", v1);
cmd.Parameters.AddWithValue("#Case_Status", v2);
Below is the aspx code for the page:
<asp:GridView ID="GridView1" runat="server" CellPadding="5" ForeColor="#333333" width="1000px"
GridLines="None" OnPageIndexChanging="gridView_PageIndexChanging"
AllowSorting="True" OnSorting="gridView_Sorting" AutoGenerateColumns="False" OnRowUpdating="GridView1_RowUpdating"
BorderStyle="Outset" CellSpacing="1" Font-Names="Cambria"
Font-Size="Small" AllowPaging="True" ShowFooter="True"
ShowHeaderWhenEmpty="True"
DataSourceID="SqlDataSource1" onselectedindexchanged="GridView1_SelectedIndexChanged"
>
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField HeaderText="Case Number" SortExpression="case_number">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("case_number") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label7" runat="server" Text='<%# Bind("case_number") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Case Name" SortExpression="case_name">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("case_name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label8" runat="server" Text='<%# Bind("case_name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Case Type" SortExpression="Case_Type_Text">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList6" runat="server"
DataSourceID="SqlDataSource2" DataTextField="Case_Type_Text"
DataValueField="Case_Type_Text" SelectedValue='<%# Bind("Case_Type_Text") %>'>
<asp:ListItem>--Select--</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label9" runat="server" Text='<%# Bind("Case_Type_Text") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Case Status" SortExpression="Case_Status_Text">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList3" runat="server"
DataSourceID="SqlDataSource3" DataTextField="Case_Status_Text" DataValueField="Case_Status_Text"
SelectedValue='<%# Bind("Case_Status_Text") %>'>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Case_Status_Text") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Assigned Date" SortExpression="assigned_date">
<EditItemTemplate>
<asp:TextBox ID="TextBox5" runat="server"
Text='<%# Bind("assigned_date", "{0:d}") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label10" runat="server"
Text='<%# Bind("assigned_date", "{0:d}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Assigned To" SortExpression="assigned_to">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList7" runat="server"
DataSourceID="SqlDataSource4" DataTextField="User_Name"
DataValueField="User_Name" SelectedValue='<%# Bind("assigned_to") %>'>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label11" runat="server" Text='<%# Bind("assigned_to") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date Withdrawn" SortExpression="date_withdrawn">
<EditItemTemplate>
<cc1:DatePicker ID="DatePicker5" runat="server" DateFormat="yyyy-MM-dd"
CalendarDate='<%# Bind("date_withdrawn") %>' TextCssClass="" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server"
Text='<%# Bind("date_withdrawn", "{0:d}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date Delivered" SortExpression="date_delivered">
<EditItemTemplate>
<cc1:DatePicker ID="DatePicker7" runat="server"
CalendarDate='<%# Bind("date_delivered") %>' TextCssClass=""
/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label6" runat="server"
Text='<%# Bind("date_delivered", "{0:d}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="QC By" SortExpression="qc_by">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList5" runat="server"
DataSourceID="SqlDataSource4" DataTextField="User_Name" DataValueField="User_Name"
SelectedValue='<%# Bind("qc_by") %>'>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("qc_by") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="QC Date" SortExpression="qc_date">
<EditItemTemplate>
<cc1:DatePicker ID="DatePicker6" runat="server"
CalendarDate='<%# Bind("qc_date") %>' TextCssClass=""
/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("qc_date", "{0:d}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Additional Notes">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"
Text='<%# Bind("additional_notes") %>' TextMode="MultiLine"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("additional_notes") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" ButtonType="Button"
CausesValidation="False" />
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
Try likes this ,
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
DropDownList ct = (DropDownList)row.Cells[2].FindControl("DropDownList6");
string ctype = ct.SelectedValue;
DropDownList cs = (DropDownList)row.Cell[3].FindControl("DropDownList3");
string cstatus = cs.SelectedValue;
GridViewRow row = grdVw.Rows[e.RowIndex];
String str = Convert.ToString(((DropDownList)(row.Cells[2].Controls[0])).SelectedItem);
Get your cell number ,Numbering for cells start from zero so it will be 2 for DropDownList6 in your code .
Please check and verify if it works !