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.
Related
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();
}
}
I am wanting to create a session in an URL and assign its value from a database.
For example i currently have URL creating a list according to the select statement.
I am wanting to include Favourite_ID but assign it to a session instead.
So something like: Session ["Fav"] = Favourite_ID;
ASP.
<asp:DataList ID="DataList1" runat="server" ShowFooter="False" ShowHeader="False" Width="460px" CellPadding="1" Height="193px">
<ItemStyle Font-Bold="False" Font-Italic="False" Font-Overline="False" Font-Strikeout="False" Font-Underline="False" />
<ItemTemplate>
<table class="auto-style2">
<tr>
<ul>
<td class="auto-style3">
<h6><li><asp:HyperLink Runat ="server" NavigateUrl ='<%#"RecipePage?id=" + DataBinder.Eval(Container.DataItem, "Recipe_ID").ToString()%>' ID="Hyperlink1"><%#DataBinder.Eval(Container.DataItem, "Recipe_Name")%></asp:HyperLink></asp></li></h6>
</td>
</ul>
</tr>
</table>
</ItemTemplate>
C#
private void loadRecipe()
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0; AttachDbFilename=C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\Student_CB.mdf ;Integrated Security=True");
con.Open();
try
{
//Fetching top recipe
string query = ("SELECT * FROM Recipe LEFT JOIN Favourite on Recipe.Recipe_ID = Favourite.Recipe_ID WHERE Favourite.Student_ID = '"+UserID.Text+"' ORDER BY Recipe_Name");
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
da.Fill(ds);
DataList1.DataSource = ds;
DataList1.DataBind();
}
catch (Exception)
{
//catch exception here
}
con.Close();
}
Also im just testing what i can do at the moment. So excuse the bad practise of not using a parameter and using Try-catch.
This will change once i understand whether i can use a session the way im hoping to.
I have used changed my current code to allow the use of a CommandArgument. In which calls and creates a session.
<asp:DataList ID="DataList1" runat="server" ShowFooter="False" ShowHeader="False" Width="460px" CellPadding="1" Height="193px">
<ItemStyle Font-Bold="False" Font-Italic="False" Font-Overline="False" Font-Strikeout="False" Font-Underline="False" />
<ItemTemplate>
<table class="auto-style2">
<tr>
<ul>
<td class="auto-style3">
<h6><li><asp:LinkButton runat="server" OnCommand="Call_Fav" CommandArgument='<%# Eval("Favourite_ID") %>' ID="bob" Text='<%#DataBinder.Eval(Container.DataItem, "Recipe_Name")%>' /></li></h6>
</td>
</ul>
</tr>
</table>
</ItemTemplate>
i want to retrieve the data stored in the table of the database into gridview control and my ado code is
public void retrieve_client()
{
SqlConnection con = new SqlConnection(DBconnection.connectstr);
con.Open();
SqlCommand com = new SqlCommand("retrieve_client", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add("#name", SqlDbType.VarChar).Value = this.name;
SqlDataReader r = com.ExecuteReader();
if(r.HasRows)
{
if(r.Read())
{
this.name = r[0].ToString();
this.address = r[1].ToString();
this.phone = r[1].ToString();
}
}
r.Close();
con.Close();
}
and my web form source is i want to enter the name in text box and retrieve the data and displaying them into grid view control please answer me:
my web form source is:
<table>
<tr>
<td>
<label class="labelclient">Name</label>
</td>
<td class="clientpadding">
<asp:TextBox ID="Textbox_retrieveclientbyname_first" runat="server" placeholder=" First Name" cssclass="textboxstyle" required="required"></asp:TextBox>
<asp:TextBox ID="Textbox_retrieveclientbyname_second" runat="server" placeholder=" Second Name" CssClass="textboxstyle" required="required"></asp:TextBox>
<asp:TextBox ID="Textbox_retrieveclientbyname_third" runat="server" placeholder=" Third Name" CssClass="textboxstyle" required="required"></asp:TextBox>
</td>
</tr>
</table>
<br />
<br />
<table>
<tr>
<td class="buttontd">
<asp:Button ID="btn_find_clientbyname" runat="server" Text="Find" CssClass="addclientbutton" OnClick="btn_find_clientbyname_Click"/>
</td>
<td>
<asp:Label ID="lbl_ermsg" runat="server" ></asp:Label>
</td>
</tr>
</table>
<div>
<asp:GridView ID="GridView_clientbyname" runat="server" >
<HeaderStyle CssClass="gridheader"/>
<RowStyle CssClass="gridrow" />
<AlternatingRowStyle cssclass="gridaltrow" />
</asp:GridView>
</div>
`
Use DataAdapter to Fill DataTable And bind the GridView With
That DataTable
public void retrieve_client()
{
SqlConnection con = new SqlConnection(DBconnection.connectstr);
con.Open();
SqlCommand com = new SqlCommand("retrieve_client", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add("#name", SqlDbType.VarChar).Value = this.name;
SqlDataAdapter da = New SqlDataAdapter(com);
DataTable dt=New DatTable();
da.Fill(dt);
con.Close();
GridView_clientbyname.DataSource=dt;
GridView_clientbyname.DataBind();
}
I have Image in ItemTemplate that will be changing according to Username (ie lblPostedBy.Text). I have written code in onItemCommand of repeater control in C# Asp.net 4.0. But not working. Will you please help me.
protected void myrepeater_ItemCommand1(object source, RepeaterCommandEventArgs e)
{
// Actually lblPostedBy is a linkbutton and lblPostedBy.Text is 'username of the commenter'.
LinkButton lblPostedBy = (LinkButton)e.Item.FindControl("lblPostedBy");
con.Open();
cmd.CommandText = "select image from " + lblPostedBy.Text + " where id=1";
// 'image' column in table stores path of image like '~/image/image1.jpg'
cmd.Connection = con;
string imageurl = (string)cmd.ExecuteScalar();
con.Close();
Image Image1 = (Image)e.Item.FindControl("Image1");
Image1.ImageUrl = imageurl;
}
and
<asp:Repeater ID="myrepeater" runat="server"
onitemcommand="myrepeater_ItemCommand1">
<HeaderTemplate>
<table width="100%" style="font: 8pt verdana">
<tr style="background-color:#3C78C3">
<th>NEWS FEED</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td valign="top">
<asp:Image ID="Image1" runat="server" Height="50px" Width="50px" />
<asp:LinkButton ID="lblPostedBy" runat="server" onclick="lblPostedBy_Click" Text='<%#DataBinder.Eval(Container,"DataItem.postedby") %>' />   says : <br />
<asp:TextBox id="txtPost" runat="server" Width="100%" textmode="multiline" text='<%#DataBinder.Eval(Container,"DataItem.scraps")%>' ReadOnly="True" BackColor="#EFF3FB" BorderStyle="None"></asp:TextBox>
<%#DataBinder.Eval(Container,"DataItem.scraptime") %>
<br />
<asp:TextBox ID="TextBox2" runat="server" Visible="False" Width="80%"></asp:TextBox>
<asp:Button ID="btnDoneComment" runat="server" Text="Done" Visible="False" onclick="btnDoneComment_Click"/>
<br />
<hr style="border:dashed 1px blue" />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
Thanks in Advance,
Regards,
Nikhil
Instead of "cmd.CommandText = "select image from " + lblPostedBy.Text;"
Shouldn't it be
cmd.CommandText = "select image from TableName where pby = '" + lblPostedBy.Text + "'";
Better yet, add a parameter
cmd.CommandText = "select image from tablename where pby = #pby"
cmd.Parameters.Add(new SalParameter("#pby", lblPostedBy.Text);