I would like to replace any null values for a field with an empty string when I select items from the database. Currently, what I have works fine in SQL Management Studio, but when I place it in my C# code's SELECT statement, the column I want to be empty if the value is null does not display. I do not see any error messages displaying.
I am still learning SQL, so I am not sure how to fix the query so that all 3 columns are displayed in the browser in the gridview regardless of whether the ThumbnailUrl field is null or not.
Any help is appreciated! Thanks!
Gridview code in the designer:
<cb:SortedGridView ID="SearchResultsGrid" runat="server" AutoGenerateColumns="False" DataKeyNames="ProductId" GridLines="None" SkinID="PagedList" Width="100%" Visible="false" >
<Columns>
<asp:TemplateField HeaderText="Thumbnail">
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:HyperLink ID="NodeImageLink" runat="server" NavigateUrl='<%# UrlGenerator.GetBrowseUrl((int)Eval("ProductId"), CatalogNodeType.Product, (string)Eval("Name")) %>'> <asp:Image ID="NodeImage" runat="server" ImageUrl='<%# Eval("ThumbnailUrl") %>' Visible='<%# !string.IsNullOrEmpty((string)Eval("ThumbnailUrl")) %>' AlternateText='<%# Eval("Name") %>' /> </asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SKU" SortExpression="Sku">
<HeaderStyle HorizontalAlign="Left" />
<ItemTemplate>
<asp:HyperLink ID="ProductSku" runat="server" Text='<%#Eval("Sku")%>' SkinID="FieldHeader" /><br />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item" SortExpression="Name" >
<HeaderStyle HorizontalAlign="Left" />
<ItemTemplate>
<asp:HyperLink ID="ProductName" runat="server" Text='<%#Eval("Name")%>' SkinID="FieldHeader" /><br />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Assigned">
<ItemStyle Width="50px" HorizontalAlign="Center" />
<ItemTemplate>
<asp:ImageButton ID="AttachButton" runat="server" CommandArgument='<%#Container.DataItemIndex%>' AlternateText="Add" ToolTip="Add" SkinID="AddIcon" OnClientClick="this.visible=false" OnClick="AttachButton_Click" Visible='<%#!IsProductLinked((int)Eval("ProductId"))%>' />
<asp:ImageButton ID="RemoveButton" runat="server" CommandArgument='<%#Container.DataItemIndex%>' AlternateText="Remove" ToolTip="Remove" SkinID="DeleteIcon" OnClientClick="return confirm('Are you sure you want to remove this item from this option?')" OnClick="RemoveButton_Click" Visible='<%#IsProductLinked((int)Eval("ProductId"))%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
There are no products that match the search text.
</EmptyDataTemplate>
</cb:SortedGridView>
This is the code:
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
if (SearchName.Text != "")
{
try
{
cmd.CommandText = "SELECT ProductID, ISNULL(ThumbnailUrl, '') AS ThumbnailUrl, Name, Sku FROM ac_Products WHERE Name LIKE '%' + #Name + '%'";
cmd.Parameters.AddWithValue("#Name", SearchName.Text);
cn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
SearchResultsGrid.DataSource = dt;
SearchResultsGrid.DataBind();
SearchResultsGrid.Columns[0].Visible = ShowImages.Checked;
}
catch (Exception x)
{
Logger.Error(ErrLoc + " PopulateSearchGrid(): ", x);
errorLbl2.Text = "PopulateSearchGrid() Name Search Error: " + x.Message.ToString();
}
finally
{
cn.Close();
}
}
I'm not quite sure what you mean by "does not display". An empty value actually doesn't display anything. I doubt that this is an SQL problem, as your statement looks fine (apart from what I write at the bottom about parameterizing your query). I guess it is a binding problem. You can try one of the following:
Instead of ISNULL(ThumbnailUrl, '') AS ThumbnailUrl try ISNULL(ThumbnailUrl, '-') AS ThumbnailUrl and check whether you see the - now.
If this is a Windows Forms application you can try to add the columns to the grid in the designer and set the AutoGenerateColumns property to false. Please note that you can set this property only in code, not in the designer.
If this is WPF, check whether you actually have a column definition for the required field. Maybe you have a typo on the binding configuration? The binding names are case sensitive! If you return ThumbnailUrl from the database, the binding ThumbNailUrl will not work.
As a side note: Thumbs up for trying to use parameterized queries, but it don't think you're doing it right in this case. It should read like this:
cmd.CommandText = "SELECT ProductID, ISNULL(ThumbnailUrl, '') AS ThumbnailUrl, Name, Sku FROM ac_Products WHERE Name LIKE #Name";
cmd.Parameters.AddWithValue("#Name", String.Format("%{0}%", SearchName.Text));
Related
I want to Update An Number of goals That a Player Scored so if he socred a goal I want to do an update for his number of goals...
I got an Error in my Code And I don't know how to fix it. Can anyone help me to fix it, please?
My Asp.net Code:
string connectionStr = #"Provider=Microsoft.Jet.OleDb.4.0;Data Source=|DataDirectory|\SoccerDataBase.mdb";
using (OleDbConnection sqlCon = new OleDbConnection(connectionStr))
{
sqlCon.Open();
string queryStr = "SELECT Achievement FROM SoccerAchievements WHERE UserID";
OleDbCommand sqlCmd = new OleDbCommand(queryStr, sqlCon);
sqlCmd.Parameters.AddWithValue("#AchNums", (SoccerTable.FooterRow.FindControl("txtAchNumsFooter") as TextBox).Text.Trim());
OleDbDataAdapter dataAdapt = new OleDbDataAdapter(sqlCmd);
DataSet ds = new DataSet();
dataAdapt.Fill(ds, "SoccerAchievement");
DataRow row = ds.Tables["SoccerAchievement"].Rows[0];
int a = int.Parse((SoccerTable.FooterRow.FindControl("txtAchNumsFooter") as TextBox).Text.Trim());
a = a + int.Parse("#AchNums");
string query = "UPDATE SoccerAchievements SET Achievement= '" + a + "' WHERE UserID";
sqlCmd.ExecuteNonQuery();
My HTML Code:
<asp:GridView ID="SoccerTable" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px"
CellPadding="3" DataSourceID="AccessDataSource1">
<Columns>
<asp:BoundField DataField="ID" HeaderText="קוד שחקן" InsertVisible="False"
SortExpression="ID" />
<asp:BoundField DataField="Team" HeaderText="קבוצות" SortExpression="Team" />
<asp:BoundField DataField="Players" HeaderText="שחקנים"
SortExpression="Players" />
<asp:TemplateField HeaderText="הישגים">
<ItemTemplate>
<asp:DropDownList ID="AchNums" runat="server">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
<asp:ListItem>5</asp:ListItem>
<asp:ListItem>6</asp:ListItem>
<asp:ListItem>7</asp:ListItem>
<asp:ListItem>8</asp:ListItem>
<asp:ListItem>9</asp:ListItem>
<asp:ListItem>10</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAchNumsFooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button class = "AddButton" ID="AddButton" runat="server" onclick="AddButton_Click" Text="עדכן" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
My Problem: Input string was not in the correct format.
Please help me guys :(
If you're looking to default to 0 on an empty textbox:
int i = string.IsNullOrEmpty((SoccerTable.FooterRow.FindControl("txtAchNumsFooter") as TextBox).Text.Trim()) ? 0 : int.Parse((SoccerTable.FooterRow.FindControl("txtAchNumsFooter") as TextBox).Text.Trim());
If you're looking to default to 0 with any bad formatted input:
int i;
if (!int.TryParse((SoccerTable.FooterRow.FindControl("txtAchNumsFooter") as TextBox).Text.Trim(), out i)) i = 0;
#Alex It seems to be like a format exception at the line
int a = int.Parse((SoccerTable.FooterRow.FindControl("txtAchNumsFooter") as TextBox).Text.Trim());.
In your case, the possibility is that the value return by the textbox is not a valid integer value. Thats why you are getting this error.
Can you try debugging your code and do quickwatch on this statement 'SoccerTable.FooterRow.FindControl("txtAchNumsFooter") as TextBox).Text.Trim()'. Check what you get.
I have setup a stored procedure that uses one input parameter (#QuestionID) to retrieve a single record (record comes from elements of multiple data tables).
Have created a datareader and am populating values on my web page with these values.
What I don't know how to do is to set the value of the input parameter off of someone clicking the link to open the "details" page from a list (on the referring page).
Referring page where someone clicks the details record and the QuestionID is set:
<asp:GridView ID="GridView1" runat="server" Caption="Submitted Questions" AllowSorting="True"
CaptionAlign="Left" EmptyDataText="You have not submitted any Questions." PageSize="5"
AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="QuestionID" runat="server" Text='<%# Eval("QuestionID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="KeyObjective" HeaderText="Key Objective" ItemStyle-Width="150" />
<asp:BoundField DataField="SubmitDate" HeaderText="Submitted Date" ItemStyle-Width="50" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="Details" runat="server" Text="View Details" PostBackUrl='<%# "~/Submit/Submit_Detail.aspx?Id=" + Eval("QuestionID") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="Clone" runat="server" Text="Create Clone" PostBackUrl='<%# "~/Submit/Submit_Clone.aspx?Id=" + Eval("QuestionID") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
DataReader control that is currently hardcoded to #QuestionID value of 1, I need to get this to accept the querystring value being sent from the referring page:
string sConstr = ConfigurationManager.ConnectionStrings["CS1"].ConnectionString;
SqlConnection Conn = new SqlConnection(sConstr);
using (Conn)
{
SqlCommand command = new SqlCommand("QuestionDetail", Conn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#QuestionID", SqlDbType.BigInt));
command.Parameters["#QuestionID"].Value = 1;
Conn.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
txt_author.Text = reader["Author"].ToString();
reader.Close();
}
You should be able to read it from the Request object assuming it matches the URLs provided within your LinkButtons (i.e. the querystring parameter is "Id") :
command.Parameters["#QuestionID"].Value = Convert.ToInt32(Request["Id"]);
You would just need to adjust this accordingly if your parameter was something different.
I have a grid view and when i click on the radiobutton approve it should update the recommend tag value to 1 based on the employeeID.However I am getting an error saying that object is not set to an instance of an object..My columns are also being added to the left..instead of right..Below is the code I have tried.
C# code
public void GridViewBind()
{
dadapter = new SqlDataAdapter("SELECT M_Emp_Personal.EmpName, M_Division.DivShort, M_Designation.DesigShort, T_TADA_tempform.BasicSalary, T_TADA_tempform.GPFNo, T_TADA_tempform.Gradepay,T_TADA_tempform.move_date, T_TADA_tempform.purpose, M_City.CityDesc, T_TADA_tempform.estt_visited, T_TADA_tempform.duration_stay, M_mode.mode_type, T_TADA_tempform.duration_unit, T_TADA_tempform.place, T_TADA_tempform.authority, T_TADA_tempform.exp_debited, T_TADA_tempform.reason FROM T_TADA_tempform INNER JOIN M_Emp_Personal ON T_TADA_tempform.EmpID = M_Emp_Personal.EmpID INNER JOIN M_Division ON T_TADA_tempform.DivisionID = M_Division.DivisionID INNER JOIN M_Designation ON M_Emp_Personal.DesigID = M_Designation.DesigID INNER JOIN M_City ON T_TADA_tempform.CityID = M_City.CityID INNER JOIN M_mode ON T_TADA_tempform.mode_ID = M_mode.mode_ID where M_Emp_Personal.EmpID=" + ddlname.SelectedValue + "", conn);
dset = new DataSet();
dadapter.Fill(dset);
GridView1.DataSource = dset.Tables[0];
GridView1.DataBind();
}
protected void submit_info(object sender, EventArgs e)
{
GridViewRow grow = (GridViewRow)(sender as Control).Parent.Parent;
RadioButton rbpApprove = (RadioButton)grow.FindControl("rbtnapprove");
RadioButton rbpReject = (RadioButton)grow.FindControl("rbtnreject");
if (rbpApprove.Checked == true)
{
conn.Open();
SqlCommand cmd = new SqlCommand("UPDATE T_TADA_tempform SET Recommened_tag =1 where EmpID=#EmpID", conn);
cmd.Parameters.AddWithValue("#EmpID", ddlname.SelectedValue);
conn.Close();
}
this is my ASP.NET code
<asp:GridView ID="GridView1" runat="server" CssClass="vutblrow" TabIndex="6"
CellPadding="4" ForeColor="#333333" GridLines="None" Width="100%"
PagerStyle-Mode="NumericPages" >
<PagerStyle CssClass="pgr" Height="25px" BorderStyle="Solid" />
<Columns>
<asp:TemplateField HeaderText="Approve">
<ItemTemplate>
<asp:RadioButton runat="server" GroupName="status" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Reject">
<ItemTemplate>
<asp:RadioButton runat="server" GroupName="status" />
</ItemTemplate>
</asp:TemplateField><asp:TemplateField HeaderText="Submit">
<ItemTemplate>
<asp:Button CssClass="btnAction" Text="Sumbit" runat="server" OnClick="submit_info" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle CssClass="vutblhdr" />
</asp:GridView>
You will see that error when you're trying to use an object that hasn't been initialised correctly.
Likely candidates are:
RadioButton rbpApprove = (RadioButton)grow.FindControl("rbtnapprove");
RadioButton rbpReject = (RadioButton)grow.FindControl("rbtnreject");
If the rbpApprove Control isn't found then this line here:
if (rbpApprove.Checked == true)
Will give you the error you are getting.
However only seeing a subset of your code it could be elsewhere.
I think you are missing the Ids of the radionbuttons, try this
<asp:TemplateField HeaderText="Approve">
<ItemTemplate>
<asp:RadioButton ID="rbtnapprove" runat="server" GroupName="status" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Reject">
<ItemTemplate>
<asp:RadioButton ID="rbtnreject" runat="server" GroupName="status" />
</ItemTemplate>
</asp:TemplateField>
And call Execute
if (rbpApprove.Checked == true)
{
conn.Open();
SqlCommand cmd = new SqlCommand("UPDATE T_TADA_tempform SET Recommened_tag =1 where EmpID=#EmpID", conn);
cmd.Parameters.AddWithValue("#EmpID", ddlname.SelectedValue);
cmd.ExecuteNonQuery();
conn.Close();
}
I save image path and image name in myqsl database. Now I want to display images from database on asp.net data-list. I have query result like this
I want to display picture with pageName. I do some thing like this on datalst.
<asp:DataList ID="dtlistImages" runat="server" RepeatColumns="3" RepeatDirection="Horizontal"
BorderColor="#336699" BorderStyle="Solid" BorderWidth="2px">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%# Eval("pageName") %>' Font-Bold="true"
Font-Size="10pt" ForeColor="#336699" Width="100%"/>
</br>
<asp:Image ID="imgnewspaper" runat="server" ImageUrl='<%# Eval("pageNumber") %>' />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Top" />
</asp:DataList>
Code Behind:
public DataTable getData(string query)
{
MySqlConnection conn1 = new MySqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
conn1.Open();
MySqlCommand cmd = new MySqlCommand(query, conn1);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
protected void btnshow_onclick(object sender, EventArgs e)
{
string query = "select cap_newspaper_page.pageServer,cap_newspaper_page.pagePath, pageNumber,pageName,newspaper.newspaperName,newspaper_station.newspaperStationName"+
" FROM cap_newspaper_page Inner Join cap_newspaper ON cap_newspaper_page.capnewspaperID = cap_newspaper.capnewspaperID inner join newspaper on newspaper.newspaperID=cap_newspaper.newspaperID"+
" inner join newspaper_station on newspaper_station.newspaperStationID=cap_newspaper.newspaperStationID where cap_newspaper.newspaperID="+ddlNewspaper.SelectedValue+" and cap_newspaper.newspaperStationID="+ddlNewspaperStation.SelectedValue+" and cap_newspaper_page.publishDate='"+tbDate.Text+" 00:00:00'";
dtlistImages.DataSource = getData(query);
dtlistImages.DataBind();
}
but display is like this
How I can Display images also dynamically. based on query.
what does the source code for the compiled html look like? clearly the image paths must be invalid. if you check what the asp has written does this not give a strong clue as to what is wrong?
You only have pageNumber and not pagePath in your Eval
<asp:Image ID="imgnewspaper" runat="server" ImageUrl='<%# Eval("pagePath") %>' />
or
you are missing the images in your project folder printImages locally, if your are running it locally, and if you are running it on live server then also check that folder for images.
Suggestion I have achieved the same thing in the following way:
<asp:ListView ID="ImagesList" runat="server" DataKeyNames="ID" GroupItemCount="4" OnPagePropertiesChanging="ImagesList_PagePropertiesChanging">
<EmptyDataTemplate>
No Images found.
</EmptyDataTemplate>
<ItemTemplate>
<asp:ImageButton ID="MyPicture" runat="server" OnClick="MyPicture_Click" CommandArgument='<%# Eval("ID") %>' AlternateText='<%# Eval("Name") %>' ImageUrl='<%# Eval("ImagePath") %>' Autopostback="true"Width="155" Height="80" />
</ItemTemplate>
</asp:ListView>
I am creating a webpage using C# and asp.net
I have a simple sqlite database.
I have a gridview where i am displaying just simple 2 Book categories.
The two categories are
Fiction
technical
I would like to assign a link to those categories so the user can be directed to a new page.
Here is a snapshot of the data being displayed in the gridview..
where i want to add a link to Fiction and technical to redirect to a new page.
This is my dataset and gridview.
DataSet dsgrid;
dsgrid = (DataSet)Cache["GridViewDataSet"];
if (dsgrid == null)
{
dsgrid = GetDataSet(); //call function
Cache["GridViewDataSet"] = dsgrid;
}
else
{
}
//bind our cache data to a datasource
GridView1.DataSource = dsgrid.Tables[0];
GridView1.DataBind();
}
catch (Exception ex)
{
this.lblError.Text = ex.Message;
}
}
private DataSet GetDataSet()
{
String connectionString = "Data Source=" + Server.MapPath(#"~\App_Data\bookDB.db");
String selectCommand = "Select * from Category";
SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter(selectCommand, connectionString);
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
//GridView1.DataSource = ds;
// GridView1.DataBind();
return ds;
}
Thank you
Here are a few options, which one you choose will depend on the amount of flexibility you need.
Built in button column:
<asp:GridView >
<Columns>
<asp:ButtonColumn DataField="some_field" Visible="false" ButtonType="linkButton" />
</Columns>
/<asp:GridView >
Column template: (This will give you the most flexibility.)
<asp:GridView>
<Columns>
<asp:TemplateField HeaderText="Its a link!">
<ItemTemplate>
<asp:LinkButton ID="SomeName" runat="server" Text=''>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Enjoy!
this is the markup code, you have to add a hyperlink to the gridview control inside the IntemTempalte collection and add a binding expression to the text property of the contained controls
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="128px">
<Columns>
<asp:TemplateField HeaderText="Code">
<ItemTemplate>
<asp:Label ID="lblCodigo" runat="server" Text='<%#Eval("columnNae")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:HyperLink ID="link" runat="server" Text='<%#Eval("columnNae") %>' NavigateUrl="http://nudierweb.somee.com"></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You need to use HyperLinc control
<asp:HyperLink id="hyperlink1" NavigateUrl="http://www.yournavigateurl.com"
Text="Your Hyperlink text" runat="server"/>
Try like this
<asp:HyperLinkField DataTextField="Value of column you want to make as HYPERLINK" HeaderText="COLUMN NAME" runat="server" DataNavigateUrlFields="Value you want to pass to other page(fname)" DataNavigateUrlFormatString="~/demo.aspx(another page name)?fname**strong text**={0}"/>
eg:
<asp:HyperLinkField DataTextField="stid" HeaderText="stid" Target="_self" runat="server" DataNavigateUrlFields="fname" DataNavigateUrlFormatString="~/demo.aspx?fname={0}"/>