Why onitemcommand of repeater control not working in this case? - c#

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") %>' /> &nbsp 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);

Related

When trying to update a row in gridview it give the below error?

I have a GridView that displays a data from my SQL database. Yhe user has the options to update or delete the row inside the GridView. What seems to happen now is that when the user clicks on the row to update the text boxes appear where you can edit (up until this point all works as expected) but when clicking on update it crashes with the below error.
I have pointed out in the code below where the line is where it crashes.
System.NullReferenceException: 'Object reference not set to an instance of an object.'
(... as System.Web.UI.WebControls.TextBox) returned null.
This is the code I am currently using:
Code Behind
protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
int customerId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
string name = (row.FindControl("txtName") as TextBox).Text;
string email = (row.FindControl("txtEmail") as TextBox).Text;
string license = (row.FindControl("txtLicense") as TextBox).Text;
string query = "UPDATE License SET DisplayName=#DisplayName, EmailAddress=#EmailAddress, LicenseType=#LicenseType WHERE CustomerId=#CustomerId";
string constr = ConfigurationManager.ConnectionStrings["LicenseConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Parameters.AddWithValue("#CustomerId", customerId);
cmd.Parameters.AddWithValue("#DisplayName", name);
cmd.Parameters.AddWithValue("#EmailAddress", email); <-- Error here
cmd.Parameters.AddWithValue("#LicenseType", license);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
GridView1.EditIndex = -1;
this.BindGrid();
}
and:
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound"
DataKeyNames="CustomerId" OnRowEditing="OnRowEditing" OnRowCancelingEdit="OnRowCancelingEdit" PageSize="3"
OnRowUpdating="OnRowUpdating" OnRowDeleting="OnRowDeleting" EmptyDataText="No records has been added."
Width="450">
<Columns>
<asp:TemplateField HeaderText="Display Name" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text=''
<%# Eval("DisplayName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text=''
<%# Eval("DisplayName") %>' Width="140"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email Address" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblEmailAddress" runat="server" Text=''
<%# Eval("EmailAddress") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmailAddress" runat="server" Text=''
<%# Eval("EmailAddress") %>' Width="140"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="License Type" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblLicense" runat="server" Text=''
<%# Eval("LicenseType") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLicenseType" runat="server" Text=''
<%# Eval("LicenseType") %>' Width="140"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true"
ItemStyle-Width="150" />
</Columns>
</asp:GridView>
<table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse">
<tr>
<td style="width: 150px">
Name:<br />
<asp:TextBox ID="txtName" runat="server" Width="250" />
</td>
<td style="width: 150px">
Email Address:<br />
<asp:TextBox ID="txtEmail" runat="server" Width="250" />
</td>
<td style="width: 150px">
Country:<br />
<asp:TextBox ID="txtLicense" runat="server" Width="140" />
</td>
<td style="width: 150px">
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="Insert" />
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
Am not sure why this is giving me this error
Your Textbox-Name is "txtEmailAddress" not "txtEmail".

Repeater Control, Insert

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();
}
}

Passing value of textbox to a class VS2013 ASPX C#

I have a Gridview.aspx, Gridview.aspx.cs and GetData.cs (class)
In Gridview.aspx I have a textbox named SearchData and a button named SearchBtn
I have this in my Gridview.aspx.cs >>>
protected void SearchBtn_Click(object sender, EventArgs e){
if (!IsPostBack){
Search_Grid();
}
}
void Search_Grid(){
DataGridView.DataSource = obj.Search_Data();
DataGridView.DataBind();
}
And since it's my first time to use a class, here's what i put in GetData.cs >>>
public DataTable Search_Data(){
adap = new SqlDataAdapter("select * from MyTable " +
"where MyID = '" +
value_of_my_SearchData_textbox +
"'", con);
dt = new DataTable();
adap.Fill(dt);
return dt;
}
ASPX Code
GridView.aspx code is long, but here's what under the gridview part:
<table id="TBL_GridView" runat="server" align="center">
<tr>
<td text-align:center">*** TEST ONLY ***</td>
</tr>
<tr>
<td >
<asp:Label ID="Label1" runat="server" Text="Procedure name: "></asp:Label>
<asp:TextBox ID="SearchData" runat="server"></asp:TextBox>
<asp:Button ID="SearchBtn" runat="server" Text="Search" OnClick="SearchBtn_Click" />
</td>
</tr>
<tr >
<td >
<asp:GridView ID="DataGridView" runat="server" AutoGenerateColumns="False" ShowFooter="True"
CellPadding="4" ForeColor="#333333" GridLines="None" Height="281px" style="margin-top: 0px" Width="1000px"
OnRowCancelingEdit="DataGridView_RowCancelingEdit"
OnRowEditing="DataGridView_RowEditing" HorizontalAlign="Center" >
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>Recipe Name</HeaderTemplate>
<ItemTemplate><asp:Label ID="recpname" runat="server" Text='<%# Bind("recpname")%>'></asp:Label></ItemTemplate>
<EditItemTemplate><asp:TextBox ID="recpname" runat="server"></asp:TextBox></EditItemTemplate>
<FooterTemplate><asp:TextBox ID="recpname" runat="server"></asp:TextBox></FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>Standard Time</HeaderTemplate>
<ItemTemplate><asp:Label ID="stdtime" runat="server" Text='<%# Bind("stdtime")%>'></asp:Label></ItemTemplate>
<EditItemTemplate><asp:TextBox ID="stdtime" runat="server"></asp:TextBox></EditItemTemplate>
<FooterTemplate><asp:TextBox ID="stdtime" runat="server"></asp:TextBox></FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>Operation</HeaderTemplate>
<ItemTemplate>
<asp:Button ID="BtnEdit" runat="server" Text="Edit" CommandName="Edit" Width="60px" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="BtnUpdate" runat="server" Text="Update" CommandName="Update" Width="60px" />
<asp:Button ID="BtnCancle" runat="server" Text="Cancel" CommandName="Cancel" Width="60px" />
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="BtnInsert" runat="server" Text="Insert" Width="60px" OnClick="BtnInsert_Click" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</td>
</tr>
</table>
How should I pass the value of my textbox to my class?
I see that your text box SearchData is just an ordinary textbox outside of gridview and not in the gridview.
You can simply use:
SearchData.Text
Change the methods to pass SearchData.Text
protected void SearchBtn_Click(object sender, EventArgs e){
if (!IsPostBack){
Search_Grid(SearchData.Text);
}
}
void Search_Grid(string searchValue){
DataGridView.DataSource = obj.Search_Data(searchValue);
DataGridView.DataBind();
}
Finally use it:
public DataTable Search_Data(string searchValue){
adap = new SqlDataAdapter("select * from MyTable " +
"where MyID = '" +
searchValue +
"'", con);
dt = new DataTable();
adap.Fill(dt);
return dt;
}
However, note this code is prone to SQL Injection attack because you are adding value inline, so an attacker can add ; delete from my table to wipe your data.
You should parameterize your query.
adap = new SqlDataAdapter("select * from MyTable where MyID = #myIdValue", con);

Why is one section of code working, but the other not?

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.

how to auto complete textbox in gridview?

i have gridview textbox columnns,
i need to auto complete textbox in grridview...
my code is,
<table style="width: 700px;">
<tr>
<th colspan="3">Medicine Detail :
</th>
</tr>
<tr>
<td colspan="3">
<script type="text/javascript">
$(function () {
var availableTags = [ <%= SuggestionList %>];
$("#<%= txtMedName.ClientID %>").autocomplete({
source: availableTags
});
});
</script>
<asp:GridView ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false" Width="700px" HorizontalAlign="Center"
OnRowDeleting="Gridview1_RowDeleting">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="S.No" />
<asp:TemplateField HeaderText="Medicine Name">
<ItemTemplate>
<asp:TextBox ID="txtMedName" runat="server" CssClass="TextBox"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField> </Columns>
</asp:GridView>
</td>
</tr>
<tr>
<td colspan="2"> </td>
<td>
<asp:Button ID="Button7" runat="server" Text="Add" CssClass="button" OnClick="Button7_Click" />
<asp:Button ID="Button8" runat="server" Text="Cancel" CssClass="button" PostBackUrl="~/PatientEntry.aspx" />
</td>
</tr>
</table>
my .cs code is,
public string SuggestionList = ""; string queryString = "select * from NewMedicineMaster";
using (SqlConnection con = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["HospitalConnection"].ConnectionString))
{
using (SqlCommand command = new SqlCommand(queryString, con))
{
con.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
if (string.IsNullOrEmpty(SuggestionList))
{
SuggestionList += "\"" + reader["MedName"].ToString() + "-" + reader["MedId"].ToString() + "\"";
}
else
{
SuggestionList += ", \"" + reader["MedName"].ToString() + "-" + reader["MedId"].ToString() + "\"";
}
}
}
}
}
but error came like,
The Name 'txtMedName' does not exist in the current context
<input type="text" values="<%# Eval('txtMedName')%>'">

Categories

Resources