I have to ask about A question in C#,Asp.net... i created 3 textbox for empid, name and Address
If i Click the "Edit Button" with manually type empid in a text box. i want to assign other two values name & Address to their textbox. then after i use update button to update
Can anyone teach me with code?
//Asp.net
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Empid" Width="50px"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:Label ID="Label2" runat="server" Text="Name" Width="50px"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<asp:Label ID="Label3" runat="server" Text="Address" Width="50px"></asp:Label>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<br />
<br />
<br />
<br />
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
<br />
</div>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="update " />
<asp:Button ID="Button2" runat="server" Text="Edit" Width="61px" />
</form>
//Cs for update button
SqlConnection conn = new SqlConnection("Data Source=s\\SQLEXPRESS;Initial catalog = sample;Integrated security=True");
SqlCommand cmd = new SqlCommand("UPDATE empdetails SET Name='" + TextBox2.Text + "',Address='" + TextBox3.Text + "' WHERE Empid ='" + TextBox1.Text + "'", conn);
conn.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT * FROM Empdetails";
GridView.DataSource = cmd.ExecuteReader();
GridView.DataBind();
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
conn.Close();
I code like this ,if i Edit Button, with entered Empid, i want other values name & Address ll assign to text box
Steps:
Get the Employee details in GridView.
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
GetEmpDetails()
End Sub
Private Sub GetEmpDetails()
SqlConnection conn = new SqlConnection("Data Source=s\\SQLEXPRESS;Initial catalog = sample;Integrated security=True");
conn.Open();
cmd.CommandText = "SELECT * FROM Empdetails";
GridView.DataSource = cmd.ExecuteReader();
GridView.DataBind();
End Sub
Add this Property AutoGenerateSelectButton="True" to the gridview in the design page.
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
AutoGenerateSelectButton="True"
CellPadding="4" >
</asp:GridView>
On the SelectedIndexChanged of the Grid get the RowIndex so that we will get the row value of the row selected.
Protected Sub GridView1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles GridView1.SelectedIndexChanged
LoadValues(GridView1.SelectedRow.RowIndex)
End Sub
Then Load the grid values to the respective textbox.
And change the values you want but don't change the ID (Highly recommended)
Then Click UpdateButton. Call Update Query there.
Load grid value again and bind it. So that you can see the change instantly.
Happy Coding..!! :)
Related
I'm working in a Quiz Page where users can access and answers some questions. The problem I'm facing is when I want to display the possible answers of the questions. I want to display the options in a dropdownlist. I already have the questions in a datalist. Are there any ideas of how can I do it?
This is how it looks:
(In the arrows that I placed is where I want to display the options)
This is what users see
Here is what I have:
A FormQuiz.aspx:
<body style="background-color: #0f5298">
<form id="form1" runat="server">
<nav class="auto-style2" style="background-color: #d5f3fe">
<div class="auto-style3">
<a class="navbar-brand" href="#">
<img src="logo.png" alt="" class="auto-style1" />
Quiz
</a>
</div>
</nav>
<div class="card">
<asp:Label ID="LabelName" runat="server" Text="Seleccione un Quiz:" CssClass="lbl"></asp:Label>
<asp:DropDownList ID="DropDownList1" runat="server" CssClass="ddl" AppendDataBoundItems="true" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" >
<asp:ListItem Text="--- Seleccione ----" Value=" " />
</asp:DropDownList>
<asp:Label ID="Label1" runat="server" Text="Instrucciones" CssClass="lbl"></asp:Label>
<asp:Label ID="LabelInstrucciones" runat="server" CssClass="I"></asp:Label>
<asp:Panel ID="Panel1" runat="server" CssClass="panelQ">
<asp:Label ID="Label2" runat="server" CssClass="section"></asp:Label>
<asp:DataList ID="DataList1" runat="server" CssClass="datalist">
<ItemTemplate>
<div style="margin-top: 2%">
<asp:Label ID="Label2" runat="server" Text='<%#Eval("Description") %>'></asp:Label>
</div>
<asp:DropDownList ID="DropDownOptions" runat="server" Width="200px" AppendDataBoundItems="true" AutoPostBack="true" DataSourceID="dsOptions" DataTextField="Options" DataValueField="Id">
<asp:ListItem></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:DataList>
</asp:Panel>
</div>
</form>
</body>
This is how I get the questions in FormQuiz.aspx.cs:
public void SelectedSectionsTitlesQuestions(int id)
{
using (SqlConnection con = new SqlConnection(connectionstring))
{
con.Open();
string querySection = #"SELECT Mant.Sections.Name
FROM Mant.Quizzes
INNER JOIN Mant.Questions ON Mant.Quizzes.Id = Mant.Questions.Quiz_Id
INNER JOIN Mant.Sections ON Mant.Questions.Section_Id = Mant.Sections.Id
WHERE Mant.Quizzes.Id =" + id;
string queryQuestion = #"SELECT Mant.Questions.Description
FROM Mant.Quizzes
INNER JOIN Mant.Questions ON Mant.Quizzes.Id = Mant.Questions.Quiz_Id
WHERE Mant.Quizzes.Id =" + id;
SqlDataAdapter ad2 = new SqlDataAdapter(querySection, con);
DataSet ds2 = new DataSet();
ad2.Fill(ds2);
Label lblsection = (Label)FindControl("Label2");
lblsection.Text = ds2.Tables[0].Rows[0]["Name"].ToString(); ;
DataList datalistQuestions = (DataList)FindControl("DataList1");
SqlDataAdapter ad = new SqlDataAdapter(queryQuestion, con);
DataSet ds = new DataSet();
ad.Fill(ds);
datalistQuestions.DataSource = ds;
datalistQuestions.DataBind();
FillDropdown();
con.Close();
}
}
This is how I populate the dropdown with a SqlDataSource:
public void FillDropdown()
{
using (SqlConnection con = new SqlConnection(#"Server =hncrsap-sql01; Database=HEDS;User Id = sa; Password=Lear2005; MultipleActiveResultSets=true;"))
{
con.Open();
List<int> Types = new List<int>(TypeQuestionsId());
for(int x=0; x < Types.Count(); x++)
{
int TQuestions_Id = Types[x];
string queryTypeQuestion = #"SELECT TypeQuestions_Id
FROM Mant.Questions
WHERE Quiz_Id=" + id_Quiz +
"AND TypeQuestions_Id=" + TQuestions_Id;
SqlCommand SelectCommand = new SqlCommand(queryTypeQuestion, con);
SqlDataReader myreader;
myreader = SelectCommand.ExecuteReader();
while (myreader.Read())
{
string querySelectOptions = #"SELECT Options, Id
FROM Mant.AnswerOptions
WHERE TypeQuestions_Id=" + TQuestions_Id;
SqlDataSource dsOptions = new SqlDataSource();
dsOptions.ID = "dsOptions";
this.Page.Controls.Add(dsOptions);
dsOptions.ConnectionString = "Server =hncrsap-sql01; Database=HEDS;User Id = sa; Password=Lear2005; MultipleActiveResultSets=true;";
dsOptions.SelectCommand = querySelectOptions;
}
}
con.Close();
}
// return values;
}
But I got this error in the SelectedSectionsTitlesQuestions method
You can configure another SqlDataSource and bind it to your drop-down list.
<asp:DropDownList ID="ddlEmployees" runat="server" DataSourceID="SqlDataSource1"
DataTextField="EmployeeName" DataValueField="EmployeeID" AppendDataBoundItems="true">
<asp:ListItem Text="Please select" Value="" />
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DB_9EF896_weddingConnectionString %%>"
SelectCommand="SELECT (FirstName + ' ' + LastName) AS EmployeeName, EmployeeID FROM Employees">
</asp:SqlDataSource>
Result
As you can see in the photo, the selected row value doesnt match in the dropdown.
I have gridview filled with data from database and when you click a certain row the value from the gridview row will be inserted inside the input box/dropdown, after that the user can edit/manipulate the values and when they click save it will update the selected gridview row with the changes that they made. The values inside the dropdown list I created are also being fetch from the database. my problem is that when the user click on a certain row, the value of the dropdown list should be the same value with the value of the selected row. (example : row_1 has the value "cat" when i select the row_1 the dropdown value must change to cat also.) and the other one is that when i choose to change the value inside the selected gridview using the dropdown, it should update(example: using the dropdown, (I change value"cat" to "dog", after i click save the selected griview row should be updated to dog)
this is the gridview code
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="CASE_KEY" DataSourceID="SqlDataSource1" Height="250px"
Width="1109px" BackColor="White" BorderColor="#999999" BorderStyle="None"
BorderWidth="1px" CellPadding="3" GridLines="Vertical" onrowcommand="GridView1_RowCommand"
OnRowDataBound="GridView1_RowDataBound">
<AlternatingRowStyle BackColor="Gainsboro" />
<Columns>
<asp:buttonfield buttontype="Link" commandname="Select" text="Select" Visible="False" />
<asp:BoundField DataField="CASE_KEY" HeaderText="CASE_KEY" ReadOnly="True"
SortExpression="CASE_KEY" Visible="False" />
<asp:BoundField DataField="DEPARTMENT_CASE_NUMBER"
HeaderText="Department Case #" SortExpression="DEPARTMENT_CASE_NUMBER" />
<asp:BoundField DataField="DEPARTMENT_NAME" HeaderText="Department"
SortExpression="DEPARTMENT_NAME" />
<asp:BoundField DataField="CHARGE" HeaderText="Charge"
SortExpression="CHARGE" />
<asp:BoundField DataField="LAB_CASE" HeaderText="Lab Case #"
SortExpression="LAB_CASE" />
<asp:BoundField DataField="OFFENSE_DATE" HeaderText="Incident Report Date"
SortExpression="OFFENSE_DATE" />
</Columns>
This is the Input fields/dropdown and save
<br />
<asp:Label ID="Label2" runat="server" Font-Bold="True" Font-Names="Arial"
Font-Size="Small" Text="Case Details"></asp:Label>
<br />
<table class="style2" >
<tr>
<td class="style3" >Department Case #</td>
<td> <asp:TextBox ID="TextBox1" runat="server" Enabled="False" ontextchanged="btnCancel_Click"></asp:TextBox></td>
</tr>
<tr>
<td class="style3">Department</td>
<td>
<asp:DropDownList ID="DropDownList1" runat="server"
Height="18px" Width="153px" Enabled="False">
</asp:DropDownList>
</td>
</tr>
<tr>
<td class="style3">Charge</td>
<td>
<asp:DropDownList ID="DropDownList2" runat="server"
Height="22px" Width="153px" Enabled="False">
</asp:DropDownList>
</td>
</tr>
<tr>
<td class="style3">Lab Case #</td>
<td><asp:TextBox ID="TextBox4" runat="server" Enabled="False" ontextchanged="btnCancel_Click"></asp:TextBox></td>
</tr>
<tr>
<td class="style3">Incident Report Date</td>
<td><asp:TextBox ID="TextBox5" runat="server" Enabled="False" ontextchanged="btnCancel_Click"></asp:TextBox></td>
</tr>
</table>
<asp:TextBox ID="TextBox6" runat="server" Visible="False"></asp:TextBox>
<br />
<asp:Button ID="btnEdit" runat="server" onclick="btnEdit_Click" Text="Edit" />
<asp:Button ID="btnSave" runat="server" onclick="btnSave_Click" Text="Save" Enabled="false"/>
<asp:Button ID="btnCancel" runat="server" onclick="btnCancel_Click" Text="Cancel" Enabled="false"/>
<br />
Code behind
protected void Page_Load(object sender, EventArgs e)
{
string connetionString;
SqlConnection cnn;
connetionString = #"Data Source=A**SE****D***\MSSQL****;Initial Catalog=****;User
ID=****;Password=****";
cnn = new SqlConnection(connetionString);
cnn.Open();
DropDownList1.DataSource = SqlDataSource1;
DropDownList1.DataBind();
DropDownList1.DataTextField = "DEPARTMENT_NAME";
DropDownList1.DataValueField = "DEPARTMENT_CODE";
DropDownList1.DataBind();
DropDownList2.DataSource = SqlDataSource1;
DropDownList2.DataBind();
DropDownList2.DataTextField = "CHARGE";
DropDownList2.DataValueField = "OFFENSE_CODE";
DropDownList2.DataBind();
}
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{ ///<summary> Change the mouse cursor to Hand symbol to show the user the cell is selectable</summary>
e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='underline';this.style.cursor='Pointer'";
e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
///<summary> Attach the click event to each cells</summary>
e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.GridView1, "Select$" + e.Row.RowIndex);
}
}
protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked.
if (e.CommandName == "Select")
{
///<summary>
///Convert the row index stored in the CommandArgument
///property to an Integer.
///</summary>
int index = Convert.ToInt32(e.CommandArgument);
///<summary>
/// Retrieve the row that contains the button clicked
/// by the user from the Rows collection.
///</summary>
GridViewRow row = GridView1.Rows[index];
///<summary> Populate the input box with the value of selected row.</summary>
GridViewRow gr = GridView1.Rows[index];
TextBox1.Text = gr.Cells[2].Text;
**THIS IS WHERE I HAVE A PROBLEM**
DropDownList1.Text = gr.Cells[3].Text;
DropDownList2.Text = gr.Cells[4].Text;
TextBox4.Text = gr.Cells[5].Text;
TextBox5.Text = gr.Cells[6].Text;
TextBox6.Text = gr.Cells[1].Text;
}
}
protected void btnSave_Click(object sender, EventArgs e)
{ ///<summary> Disabling/Enabling of input fields and button when a certain button is clicked</summary>
SetEnable(false);
string connetionString;
SqlConnection cnn;
connetionString = #"Data Source=AACSERVERDELL\MSSQL2014;Initial Catalog=VADFS;User ID=vadfs;Password=vadfs";
cnn = new SqlConnection(connetionString);
cnn.Open();
SqlCommand cmd = new SqlCommand("Update TV_LABCASE Set DEPARTMENT_CASE_NUMBER=#DEPARTMENT_CASE_NUMBER,DEPARTMENT_NAME=#DEPARTMENT_NAME,CHARGE=#CHARGE,LAB_CASE=#LAB_CASE,OFFENSE_DATE=#OFFENSE_DATE where CASE_KEY=#CASE_KEY", cnn);
cmd.Parameters.AddWithValue("#DEPARTMENT_CASE_NUMBER", TextBox1.Text);
cmd.Parameters.AddWithValue("#LAB_CASE", TextBox4.Text);
**THIS IS WHERE I HAVE A PROBLEM**
cmd.Parameters.AddWithValue("#DEPARTMENT_NAME", DropDownList1.ToString());
cmd.Parameters.AddWithValue("#CHARGE", DropDownList2.ToString());
cmd.Parameters.AddWithValue("#OFFENSE_DATE", TextBox5.Text);
cmd.Parameters.AddWithValue("#CASE_KEY", TextBox6.Text);
cmd.ExecuteNonQuery();
cnn.Close();
GridView1.DataBind();
}
SQL QUERY
< asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:VADFSConnectionString %>" SelectCommand="SELECT TOP 10
C.CASE_KEY, C.DEPARTMENT_CASE_NUMBER, D.DEPARTMENT_NAME, O.OFFENSE_DESCRIPTION AS CHARGE, LAB_CASE,
OFFENSE_DATE, C.DEPARTMENT_CODE,C.OFFENSE_CODE
FROM TV_LABCASE C
INNER JOIN TV_DEPTNAME D ON C.DEPARTMENT_CODE = D.DEPARTMENT_CODE
INNER JOIN TV_OFFENSE O ON C.OFFENSE_CODE = O.OFFENSE_CODE
ORDER BY C.CASE_DATE DESC"
></asp:SqlDataSource>
You need to use SelectedValue Property of DropdownList
You may bind your ddl Like
DropDownList1.DataTextField = "DEPARTMENT_NAME";
DropDownList1.DataValueField = "DEPARTMENT_NAME";
And
DropDownList2.DataTextField = "CHARGE";
DropDownList2.DataValueField = "CHARGE";
The after In your GridView1_RowCommand() method
DropDownList1.SelectedValue = gr.Cells[3].Text;
DropDownList2.SelectedValue = gr.Cells[4].Text;
You need to add a listitem to dropdown lists.
// something like this.
ListItem li = new ListItem(gr.Cells[3].Text);
// add the ListItem to the dropdown.
DropDownList1.Items.Add(li);
But you should really be creating a database query that gets case details by ID. the ID is supplied to the query when you select a row in the gridview.
I am trying to insert a comment using repeater Control
my code in html
<asp:Repeater ID="repConcerns" runat="server" OnItemCommand="post" >
<ItemTemplate >
<div class="row col-md-12">
<div class="col-sm-2" style="background-color:#808080">
<asp:Image ID="Image1" runat="server" ImageUrl='<%#Eval("Pathh") %>' width="90px" Height="90px" CssClass="img-circle" title='<%#Eval("Name") %>'/> <br/><asp:LinkButton ID="LinkButton1" runat="server" Text='<%#Eval("Name") %>' CssClass="btn btn-info btn-sm" CommandName="btnMessage" CommandArgument='<%#Eval("Username") %>'></asp:LinkButton><br/>
</div>
<div class="col-sm-10" style="background-color:#808080" >
<asp:Label ID="Label1" width="100%" style="padding:7px;" runat="server" Enabled="false" Text='<%#Eval("Title") %>'> </asp:Label>
<asp:TextBox ID="txtMessage" placeholder="Empty Post" width="100%" style="padding:7px;" runat="server" Text='<%#Eval("Detail") %>' TextMode="MultiLine" Enabled="false" Height="100px"> </asp:TextBox>
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%#Eval("Sno") %>' />
<div class="bar"></div>
<asp:TextBox ID="txtcomment" runat="server" CssClass="form-control form-control-sm" placeholder="Comment / Write Openion Suggestion" TextMode="MultiLine" Height="40px"></asp:TextBox>
<asp:LinkButton ID="btn" runat="server" CssClass="btn btn-primary" CommandName="comment" CommandArgument='<%#Eval("Sno") %>' >Post</asp:LinkButton>
</div>
</div>
<div style="padding-bottom:10px;"></div>
<%--<br /> --%>
</ItemTemplate>
</asp:Repeater>
and C# code
protected void post(object source, RepeaterCommandEventArgs e)
{
if(e.CommandName== "comment")
{
a = e.CommandArgument.ToString();
SqlConnection con = new SqlConnection(strconn);
SqlCommand com = new SqlCommand();
com.CommandText = "insert into Comments(Sno,Comment,Username)values('" +a+ "','" + txtcomment.Text + "','" + username + "')";
con.Open();
}
}
I do not know how to insert into table "Comment".
I have made a "Page" in which their are wall posts. I have included an option for Comment. The comment button appears as it should with every post. But i do not know how to insert comment in table "Comment". i am trying to insert comment with corresponding "Sno" of Posts saved in HiddenField. But when i try to write Text Box id there "txtcomment.text" it gives me error. How do i insert.
I've made some amendments to you original code - note the comments:
protected void post(object source, RepeaterCommandEventArgs e)
{
if(e.CommandName== "comment")
{
//Find TextBox Control
TextBox txt = (TextBox)e.Item.FindControl("txtcomment");
var sno = e.CommandArgument.ToString();
SqlConnection con = new SqlConnection(strconn);
SqlCommand com = new SqlCommand();
com.CommandText = "INSERT INTO Comments(Sno,Comment,Username) VALUES (#SNO, #COMMENT, #USERNAME)";
com.Connection = con;
//Add Command Parameters
com.Parameters.AddWithValue("#SNO", sno);
com.Parameters.AddWithValue("#COMMENT", txt.Text);
com.Parameters.AddWithValue("#USERNAME", username);
con.Open();
//Execute Command
com.ExecuteNonQuery();
}
}
Here is the code that works:
protected void submitForMail(object sender, EventArgs e)
{
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\TravelJoansDB.mdb;";
string cmdstr = "INSERT INTO EmailList(FirstName,LastName,EmailAddress) VALUES (#FirstName, #LastName, #EmailAddress)";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
TextBox tFirstName = (TextBox)FormView1.FindControl("FirstName");
TextBox tLastName = (TextBox)FormView1.FindControl("LastName");
TextBox tEmail = (TextBox)FormView1.FindControl("EmailAddress");
con.Open();
com.Parameters.AddWithValue("#FirstName", tFirstName.Text);
com.Parameters.AddWithValue("#LastName", tLastName.Text);
com.Parameters.AddWithValue("#EmailAddress", tEmail.Text);
com.ExecuteNonQuery();
con.Close();
}
Here is the code that doesn't:
protected void UpdatePic(object sender, EventArgs e)
{
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\TravelJoansDB.mdb;";
string cmdstr = "INSERT INTO BlogEntryItems(Picture) VALUES (#UpdatedPic)";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
TextBox uPic = (TextBox)DataList1.FindControl("BEIPictureField");
con.Open();
com.Parameters.AddWithValue("#UpdatedPic", uPic.Text);
com.ExecuteNonQuery();
con.Close();
}
Here is the code containing the Datalist1 control:
<asp:AccessDataSource ID="AccessDataSource1" runat="server"
DataFile="~/App_Data/TravelJoansDB.mdb"
SelectCommand="SELECT * FROM Table2 INNER JOIN [BlogEntryItems] ON Table2.ID=BlogEntryItems.BlogID WHERE ID=#ID" >
<SelectParameters>
<asp:QueryStringParameter Name="ID" QueryStringField="ID" />
</SelectParameters>
</asp:AccessDataSource>
<asp:DataList ID="DataList1" runat="server" DataSourceID="AccessDataSource1">
<ItemStyle />
<ItemTemplate>
<table>
<tr>
<td>
<br />
<asp:Image ID="Image1" CssClass="placePicCenter" runat="server"
BorderWidth="1px"
BorderColor="#EEEEEE"
ImageUrl='<%# "PlaceImages/" + Eval("Picture") %>' /><br />
<asp:TextBox ID="BEIPictureField" runat="server" Text='<%# Bind("Picture") %>' /><br />
<asp:Button ID="UpdatePicButton" runat="server" Text="Update" OnClick="UpdatePic" />
<br />
</td>
</tr>
<tr>
<td>
<asp:Label ID="Label4" CssClass="placeBodyStyle" runat="server" Text='<%# Eval("PicText1") %>' />
</td>
</tr>
<tr>
<td>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
These blocks of code are for two different buttons on two different pages. The error I get when I run the second block of code is "Object reference not set to an instance of an object." Any help would be appreciated.
This line is the probable cause, it is failing to find the control BEIPictureField thus the "Object reference not set to an instance of an object." error
TextBox uPic = (TextBox)DataList1.FindControl("BEIPictureField");
EDIT 1
Try this:
TextBox uPic = (TextBox)DataList1.Items[1].FindControl("BEIPictureField");
you will have to rewrite your logic to find the control in each item not the DataList since it is the parent you will not find it there.
I'm looking to make a master page search return results to a GridView on another page, which also has a search button. I'd be grateful for any pointers on how to do this....
From Search Page .cs file. Following is Code on Search page and it's .cs page, search page button code, and master page search button code:
From Search Page .cs file:
if (IsPostBack)
{
OdbcConnection MyConnection = new OdbcConnection("DRIVER={MySQL ODBC 3.51 Driver}; SERVER=localhost; DATABASE=petsdat; UID=root; PASSWORD=; OPTION=3");
MyConnection.Open();
OdbcCommand MyCommand = MyConnection.CreateCommand();
MyCommand.CommandText = "SELECT * FROM pets WHERE species like '%" + txtSearch.Text + "%'";
OdbcDataReader MyDataReader = MyCommand.ExecuteReader();
grdSearch.DataSource = MyDataReader;
grdSearch.DataBind();
MyConnection.Close();
}
From Search Page:
<form id="form2" >
<div>
<h1>Search for Pets</h1>
<hr />
<asp:Label runat="server" ID="lblSearch" Text="Search"></asp:Label>
<asp:TextBox runat="server" ID="txtSearch"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtSearch" ErrorMessage="Try Again"></asp:RequiredFieldValidator>
<asp:Button runat="server" ID="btnSubmit" PostBackUrl="~/Search.aspx" Text="Submit" />
<br />
<br />
<br />
<asp:GridView runat="server" ID="grdSearch" BorderColor="#CC6600"
BorderStyle="Solid" BorderWidth="1px" Font-Names="Arial" Font-Size="Medium"
GridLines="Both" HorizontalAlign="Left" Width="600px"></asp:GridView>
<br />
<br />
<br />
<br />
<br />
<br />
</div>
</form>
</asp:Content>
Master Page Search Submit Button Code:
<asp:TextBox ID="Search1" runat="server" ></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Submit" PostBackUrl="~/Search.aspx" />
On Button1 Click event you can set the value of Search1 (TextBox) in QueryString & the do a redirect to your Search Page.
Eg.:
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("~/Search.aspx?SearchText=" + Search1.Text);
}
Also, you have to modify the Search Page Code:
string searchText = "";
if(Request.QueryString["SearchText"] != null)
searchText = Request.QueryString["SearchText"];
MyCommand.CommandText =
"SELECT * FROM pets WHERE species like '%" + searchText + "%'";