how to get rating ajax id from a data list in code behind
asp.net.The value of the rating should come from database and display
.
web form
<asp:datalist id="viewjobdetails" clientidmode="Static" runat="server" datakeynames="Job_ID">
<itemtemplate>
<ajaxtoolkit:rating id="Ratinghk" runat="server" behaviorid="RatingBehavior1"
="" currentrating="0" maxrating="5" starcssclass="ratingStar" waitingstarcssclass="savedRatingStar" filledstarcssclass="filledRatingStar" emptystarcssclass="emptyRatingStar" style="float: left;">
<asp:label id="lblRatingStatus" runat="server">
</<ajaxtoolkit></itemtemplate>
</asp:datalist>
Code Behind
if (!this.IsPostBack)
{
DataTable dt = this.GetData("SELECT ISNULL(AVG(Reviews), 0) AverageRating, COUNT(Reviews) RatingCount FROM tblHKHOReviews where HK_ID=" + Request.QueryString["ID"]);
Ratinghk.CurrentRating = Convert.ToInt32(dt.Rows[0]["AverageRating"]);
lblRatingStatus.Text = string.Format("{0} Users have rated. Average Rating {1}", dt.Rows[0]["RatingCount"], dt.Rows[0]["AverageRating"]);
}
private DataTable GetData(string query)
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(_conString))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
Related
C# code
public partial class photorecognize : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\registerdatabase.mdf;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select image from [picture] where username = 'wenhao123'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
DataListABC.DataSource = dt;
DataListABC.DataBind();
con.Close();
}
}
asp.net
<asp:DataList ID="DataListABC" runat="server" Height="208px" Width="226px">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" />
</ItemTemplate>
</asp:DataList>
Database:
The autofill works for the static text box, but not the dynamic one.
User needs to be able to add as many rows as necessary, and each text box should pull from the same table. There are too many records in the table to use a simple drop down... Any ideas?
This Works
<form id="TestForm" runat="server">
<asp:ScriptManager ID="thisNameDoesntMatter" runat="server"
EnablePageMethods="true" />
<asp:TextBox ID="noteValue" runat="server" OnTextChanged="noteValue_TextChanged" CausesValidation="true" Width="1000"></asp:TextBox>
<cc1:AutoCompleteExtender ServiceMethod="searchNoteValues"
MinimumPrefixLength="2"
CompletionInterval="100" EnableCaching="false" CompletionSetCount="10"
TargetControlID="noteValue"
ID="AutoCompleteExtenderNoteValues" runat="server" FirstRowSelected="false"/>
</form>
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> searchNoteValues(string prefixText, int count)
{
string strConn = db_connection_string_EINSTEIN;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT id, NoteValue FROM agl.GuidelineNoteValues where isActive = 1 and NoteValue like '%' + #SearchText + '%'";
cmd.Parameters.AddWithValue("#SearchText", prefixText);
con.Open();
List<string> NoteValues = new List<string>();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
NoteValues.Add(sdr["NoteValue"].ToString());
}
}
con.Close();
return NoteValues;
}
This Does Not
<form id="TestForm" runat="server">
<asp:ScriptManager ID="thisNameDoesntMatter" runat="server"
EnablePageMethods="true" />
<asp:PlaceHolder ID="TestPlaceHolder" runat="server" />
<asp:LinkButton ID="TestAddNoteButton" runat="server" Text="Add a note" OnClick="TestAddNoteButton_Click" CausesValidation="false" AutoPostBack="true"/>
</div>
</form>
Table notesTable = new Table();
protected void Page_PreRender(object sender, EventArgs e)
{
Session["table"] = notesTable;
}
public void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
notesTable.ID = "MyTable";
}
else
{
notesTable = (Table)Session["table"];
TestPlaceHolder.Controls.Add(notesTable);
}
}
protected void TestAddNoteButton_Click(object sender, EventArgs e)
{
TableRow tr = new TableRow();
TableCell tc1 = new TableCell();
TableCell tc2 = new TableCell();
string strConn = db_connection_string_EINSTEIN;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT id, name FROM agl.guidelineNoteCategories";
con.Open();
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
dAdapter.Fill(objDs);
if (objDs.Tables[0].Rows.Count > 0)
{
System.Web.UI.WebControls.ListBox lb = new System.Web.UI.WebControls.ListBox();
System.Web.UI.WebControls.TextBox tb = new System.Web.UI.WebControls.TextBox();// { ID = sna.ToString()};
tb.Width = 1000;
tb.ID = "tb";
AjaxControlToolkit.AutoCompleteExtender ace = new AjaxControlToolkit.AutoCompleteExtender();
ace.ServiceMethod="searchNoteValues";
ace.MinimumPrefixLength=2;
ace.CompletionInterval=100;
ace.EnableCaching=false;
ace.CompletionSetCount=10;
ace.TargetControlID="tb";
ace.FirstRowSelected=false;
lb.BorderColor = System.Drawing.Color.Orange;
lb.DataSource = objDs.Tables[0];
lb.DataTextField = "name";
lb.DataValueField = "id";
lb.DataBind();
lb.Items.Insert(0, "--Select--");
tc1.Controls.Add(lb);
tc2.Controls.Add(tb);
tr.Cells.Add(tc1);
tr.Cells.Add(tc2);
notesTable.Rows.Add(tr);
Session["table"] = notesTable;
ViewState["dynamictable"] = true;
}
con.Close();
}
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> searchNoteValues(string prefixText, int count)
{
string strConn = db_connection_string_EINSTEIN;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT id, NoteValue FROM agl.GuidelineNoteValues where isActive = 1 and NoteValue like '%' + #SearchText + '%'";
cmd.Parameters.AddWithValue("#SearchText", prefixText);
con.Open();
List<string> NoteValues = new List<string>();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
NoteValues.Add(sdr["NoteValue"].ToString());
}
}
con.Close();
return NoteValues;
}
}
Got it. Wasn't adding the auto complete extender to the form.
TestForm.Controls.Add(ace);
I am trying to bind a selected item from the database in dropdownlist. I am not getting the users selected data in the dropdownlist instead it loads everything. What i need is to have a default selected value from the database along with other items. Please help me to overcome this problem. Thanking you in advance.
Stored procedure:
CREATE PROCEDURE [dbo].[get_student_details]
#StudentId int = 0
AS
BEGIN
SET NOCOUNT ON;
SELECT
dbo.Student.InstituteId,
dbo.Student.Institute,
dbo.Student.Name,
dbo.Student.Gender,
dbo.Student.Age
FROM
dbo.Student
WHERE
dbo.Student.StudentId = #StudentId
END
My .aspx markup:
<asp:DropDownList ID="ddlInstitute" runat="server"></asp:DropDownList>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:TextBox ID="txtGender" runat="server"></asp:TextBox>
<asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
<asp:Button ID="btnPersonalDetails" runat="server" Text="Search" OnClick="GetStudentDetails"/>
My code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillInstitute();
}
}
public void FillInstitute()
{
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "get_Institute";
cmd.Connection = con;
try
{
con.Open();
ddlInstitute.DataSource = cmd.ExecuteReader();
ddlInstitute.DataTextField = "Institute";
ddlInstitute.DataValueField = "InstituteId";
ddlInstitute.DataBind();
ddlInstitute.Items.Insert(0, new ListItem("--Select--", "0"));
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}
public void GetStudentDetails()
{
studentid= 123;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "get_student_details";
cmd.Parameters.Add("#StudentId", SqlDbType.Int).Value = studentid;
cmd.Connection = con;
try
{
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
ddlInstitute.DataValueField= dr["InstituteId"].ToString();
ddlInstitute.DataTextField= dr["Institute"].ToString();
txtName.Text = dr["Name"].ToString();
txtGender.Text = dr["Gender"].ToString();
txtAge.Text = dr["Age"].ToString();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}
You have to use SelectedValue property of DropDownList.DataTextField and DataValueField are for specifying which properties from DataSource should be used as Text and Value of drop down list.
Replace these lines:
ddlInstitute.DataValueField= dr["InstituteId"].ToString();
ddlInstitute.DataTextField= dr["Institute"].ToString();
with:
ddlInstitute.SelectedValue= dr["InstituteId"].ToString();
or you can also do:
ddlInstitute.Items.FindByValue(dr["InstituteId"].ToString()).Selected = true;
You can also refer this article
Assuming you know which ID you want to have selected, try something like this:
ddlInstitute.Items.FindByValue(dr["InstituteId"].ToString()).Selected = true;
Try it as a function:
void FN_loadBranch()
{
classname cls = new classname ();
DataTable dt = new DataTable();
dt = cls.FUNCTIONNAMEINCLASS(int id);
dropdown.DataSource = dt;
dropdown.DataValueField = "valuefield";
dropdown.DataTextField = "textfield";
dropdown.DataBind();
ddlBranch.Items.Insert(0, new ListItem("--Select--", "0"));
}
In function:
public DataTable FUNCTIONNAMEINCLASS( int id)
{
try
{
using (SqlConnection cn = new SqlConnection(CLASS.ConnectionString))
{
SqlCommand cmd = new SqlCommand("[storedprocedure]", cn);
cn.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ID", SqlDbType.VarChar, 50).Value = id;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
}
}
Use stored procedure in the function
I have a search button on my web page and it should return the subject name from the DB which are similar to entered search word, but I didnt get any out put when I use the following code... please help me to do it...
this is my C# code
protected void Button1_Click(object sender, ImageClickEventArgs e)
{
MySqlConnection connection = new MySqlConnection("server=localhost; database=e-learningsystem; uid=root; password=123;port=3307;");
connection.Open();
string srh = editbox_search.Type;
try
{
MySqlCommand cmd = new MySqlCommand("SELECT * FROM subject WHERE Name= LIKE %'" + srh + "'%", connection);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
connection.Close();
}
catch
{
}
asp.net code:
<input name="editbox_search" class="editbox_search" id="editbox_search"
maxlength="80" type="text"
style="background-color: #99CCFF; margin-top: 0px; height: 15px;" runat="server"
enableviewstate="True" title="Search Courses:" clientidmode="Inherit"
dir="ltr" visible="True"/>
<asp:Button ID="Button1"
runat="server" Height="26px" Text="Go" Width="32px" />
<asp:GridView ID="GridView1" runat="server" ShowFooter="True"
Caption="<h3 style='background-color:teal;color:white;'>Search Results...</h3>"
BackColor="LightGoldenrodYellow" BorderColor="Tan"
BorderWidth="1px" CellPadding="2" ForeColor="Black" GridLines="None">
</asp:GridView>
There is Mistake in Your Query, Correct it as below.
MySqlCommand cmd = new MySqlCommand("SELECT * FROM subject WHERE Name LIKE '%" + srh + "%'", connection);
First, use a parameterized command to avoid SQL injections. Second, I think the value you are looking for is in the Text property of the input, not the Type property. Lastly, the single quotes go outside the matching characters, i.e., '%searchvalue%'.
protected void Button1_Click(object sender, ImageClickEventArgs e)
{
MySqlConnection connection = new MySqlConnection("connection string removed");
connection.Open();
try
{
var cmd = new MySqlCommand("SELECT * FROM subject WHERE Name LIKE '%#input%'", connection);
cmd.Parameters.Add("#input", editbox_search.Text);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
connection.Close();
}
catch (Exception e)
{
// log the exception
}
}
Try this one:
protected void Button1_Click(object sender, ImageClickEventArgs e)
{
MySqlConnection connection = new MySqlConnection("connection string removed");
connection.Open();
try
{
var cmd = new MySqlCommand("SELECT * FROM subject WHERE Name LIKE '%'+#input+'%'", connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#input", editbox_search.Text);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
MySqlDataReader dr = cmd.ExecuteReader();
da.Fill(dr);
GridView1.DataSource = dr;
GridView1.DataBind();
connection.Close();
}
catch (Exception e)
{
// log the exception
}
}
Try this query
SELECT * FROM subject WHERE Name LIKE %'" + srh + "'%
I have a grid view in which there are three fields. First is data bound field, second is template field contains text box control and third is again template field contains the FileUpload Control.
I want to disable the grid view row when file upload control completes the file upload operation.
My code for grid binding is :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class gr4 : System.Web.UI.Page
{
SqlConnection cn;
SqlCommand cmd;
SqlDataAdapter da;
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
cn = new SqlConnection("Data Source=AMIR-PC\\MOHEMMAD;Initial Catalog=CRM_InvestPlus;Integrated Security=True");
string query = "Select Capacity from Dealer_License_Capacity where ID='D00001' and Software_ID='001' and Version_ID='1'";
cn.Open();
cmd = new SqlCommand(query,cn);
da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
cn.Close();
string query1 = "select Price from Version_Master where Software_ID='001' and Version_ID='1'";
cn.Open();
cmd = new SqlCommand(query1, cn);
da = new SqlDataAdapter(cmd);
DataSet ds1 = new DataSet();
da.Fill(ds1);
cn.Close();
string query2 = "select Software_Name from Software_Master where Software_ID='001'";
cn.Open();
cmd = new SqlCommand(query2, cn);
da = new SqlDataAdapter(cmd);
DataSet ds2 = new DataSet();
da.Fill(ds2);
cn.Close();
DataTable dt = new DataTable();
// dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Software_Name", typeof(string));
dt.Columns.Add("Price", typeof(string));
int count = Convert.ToInt32(ds.Tables[0].Rows[0][0].ToString());
for (int i = 0; i < count; i++)
{
DataRow dr = dt.NewRow();
// dr["Name"] = "aaa";
dr["Software_Name"] = ds2.Tables[0].Rows[0][0].ToString();
dr["Price"] = ds1.Tables[0].Rows[0][0].ToString();
dt.Rows.Add(dr);
if (i == 0)
Response.Write(dr["Price"]);
}
GridView1.DataSource = dt;
GridView1.DataBind();
//GridView1.SelectedRow.Enabled = false;
}
}
And the source file of the Grid is :
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Software_Name" />
<asp:TemplateField>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Eval("Price") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Data is bounded perfectly but I want to disable the selected row of gridview after the file upload control completes the operation.
Please help
Thanks in advance.
protected void GridView1_DataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Enabled=false;//Check on the condition that uploaded is completed
}
}