Return multiple values from sql to label - c#

I have the label:
<asp:Label ID="lbl1" runat="server"></asp:Label>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
lbl1.Text = ImageCheck().ToString();
}
And:
protected int ImageCheck()
{
SqlConnection connection = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\***.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
string CommandText2 = "SELECT * FROM Machreta WHERE noImage = 1";
SqlCommand command2 = new SqlCommand(CommandText2, connection);
connection.Open();
int check = (int)command2.ExecuteScalar();
connection.Close();
return check;
}
How can i return multiple values? That label display only single value but there are 6 more in the table.

try this:
protected string ImageCheck()
{
var result = new StringBuilder();
using(var connection = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\***.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"))
{
string CommandText2 = "SELECT * FROM Machreta WHERE noImage = 1";
SqlCommand command2 = new SqlCommand(CommandText2, connection);
connection.Open();
using(var reader = command2.ExecuteReader())
{
while (reader.Read())
{
result.Append(reader.GetString(0));
}
}
return result.ToString();
}
}
of course is only an example and not fully solving your issue but should be a starting point :)

Here is the explanation of ExecuteScalar() method. http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar%28v=vs.71%29.aspx
"Executes the query, and returns the first column of the first row in the result set returned by the query. Extra columns or rows are ignored."
Also, SELECT * will fetch all the columns. You probably want to display multiple values for single column. Then select the column name in select statement.
SELECT xyzColumn FROM Machreta WHERE noImage = 1
Lastly, you can assign only one string to label.text. So, you will have to concatenate all these strings (multiple values for single column) and then assign it to label text. Use a reader and ExecuteReader() method instead of ExuecuteScalar().

Related

Get Id of item from dropdownlist in ASP.NET using C#

I have a dropdownlist in my project that get the value from SQL Server. Table in SQL Server has several columns and I select MemberId and MemberName from that. I want to show MemberName in the dropdown, but when I select an item, I want to get MemberId.
I do this like that:
string strsql1;
SqlConnection con1;
string strcon = "Data Source=ZAHRA\\SQLEXPRESS01;Initial Catalog=YekAye;Integrated Security=True";
con1 = new SqlConnection(strcon);
strsql1 = "SELECT MemberId,MemberName FROM TbAye WHERE StatusMember = 1 ORDER BY MemberName";
SqlCommand cmd1 = new SqlCommand(strsql1, con1);
con1.Open();
DropDownListAye.DataSource = cmd1.ExecuteReader();
DropDownListAye.DataTextField = "MemberName";
DropDownListAye.DataValueField = "MemberId";
DropDownListAye.DataBind();
con1.Close();
But this:
int SelectedMember = Convert.ToInt32(DropDownListAye.SelectedValue);
gets me the index of the selected item, not MemberId of it.
What should I do?
I found What happened.
I write this:
int SelectedMember = Convert.ToInt32(DropDownListAye.SelectedValue);
in the page_load but I should write it in :
protected void DropDownListAye_SelectedIndexChanged(object sender, EventArgs e)
{
int SelectedMember = Convert.ToInt32(DropDownListAye.SelectedValue);
}

How can i add items from database to checklist box?

I've a database project , and i'm needed to add elements from database to checklist box,, how can i do that??
this is the code i have written but its seems that it has a problem
private void CheckedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string connection_string = #"Data Source=DESKTOP-MMHA4KL;Initial Catalog=Movie rental;Integrated Security=True";
SqlConnection connection = new SqlConnection(connection_string);
string Add_to_checkbox = "SELECT name from [Actor]";
SqlCommand comm = new SqlCommand(Add_to_checkbox, connection);
connection.Open();
SqlDataReader read_name = comm.ExecuteReader();
int lastindex = 0;
while(read_name.Read())
{
string name = read_name.ToString();
checkedListBox1.Items.Add(name);
}
}
Even though there is only one field being selected in your query, you need to specify it in the read. try
string name = read_name["name"].ToString();

How to get data from SQL and write it in textbox?

I need a help.
I searched and I tried a lot but I am too bad to make it work on my project by myself.
This is code for button-Seek. I want to make Seek-button to fill textbox by respective data.
private void SeekClick(object sender, EventArgs e)
{
if (TBCusNumber.Text != "")
{
string Number = TBCusNumber.Text;
var Conn = new SqlConnection();
Conn.ConnectionString = ConfigurationManager.ConnectionStrings["WindowsFormsApp1.Properties.Settings.DataBase"].ConnectionString;
var Cmd = new SqlCommand();
Cmd.Connection = Conn;
Cmd.CommandText = "SELECT * FROM CustomerList WHERE CustomerNumber = " + Number;
var DataAdapter = new SqlDataAdapter(Cmd);
DataSet DataSet = new DataSet();
DataAdapter.Fill(DataSet, "CustomerList");
CusView.DataSource = DataSet;
CusView.DataMember = "CustomerList";
}
}
And This is the data table.
This is what happens when I put 3 in the text box and press Seek-button.
So here, I want all text boxes to be filled by the data which I searched.
You will get only one row for the query right?
So give like that,
txtFirstName.Text = DataSet.Tables[0].Rows[0]["FirstName"].ToString();
txtLasttName.Text = DataSet.Tables[0].Rows[0]["LastName"].ToString();
Like this you need to assign the values to the respective text boxes.
There are three problem need to fix.
You forget to open the connection with DB,add Conn.Open(); before you excute sql command.
You need to add parameter to prevention SQL Injection
Please use using it will help you to use external resources to return the memory.
when the DataSet be filled you can get the data then fill in textbox
You can follow like this.
private void SeekClick(object sender, EventArgs e)
{
if (TBCusNumber.Text != "")
{
string Number = TBCusNumber.Text;
using (var Conn = new SqlConnection())
{
Conn.ConnectionString = ConfigurationManager.ConnectionStrings["WindowsFormsApp1.Properties.Settings.DataBase"].ConnectionString;
using (var Cmd = new SqlCommand())
{
Cmd.Connection = Conn;
Cmd.CommandText = "SELECT * FROM CustomerList WHERE CustomerNumber = #Number";
Cmd.Parameters.AddWithValue("#Number", Number);
//You miss to add Conn.Open()
Conn.Open();
using (var DataAdapter = new SqlDataAdapter(Cmd))
{
DataSet DataSet = new DataSet();
DataAdapter.Fill(DataSet, "CustomerList");
CusView.DataSource = DataSet;
CusView.DataMember = "CustomerList";
//when the DataSet be filled you can get the data then fill in textbox
txt_firstName.Text = DataSet.Tables[0].Rows[0]["FirstName"].ToString();
}
}
}
}
}

SQL delete command advice using c#

On click button presents the following code,
For some reason it wont delete data from database, (the dropdownlist is valid) any advice or changes needed?
protected void deleteback_Click(object sender, EventArgs e)
{
// declare variables
String EditNewID = DropDownList3.SelectedItem.Value;
// set connection string to database
String connectionString = WebConfigurationManager.ConnectionStrings["ScrumString"].ConnectionString;
SqlConnection myConnection2 = new SqlConnection(connectionString);
// delete values to product backlog
myConnection2.Open();
String query = "DELETE * FROM product_backlog WHERE product_backlog.id = #id ";
SqlCommand commanddelete = new SqlCommand(query, myConnection2);
commanddelete.Parameters.AddWithValue("#id", EditNewID);
// refresh page
Page.Response.Redirect(Page.Request.Url.ToString(), true);
commanddelete.ExecuteNonQuery();
myConnection2.Close();
}
maybe you are creating one string ID instead an integer
Try something like
commanddelete.Parameters.Add("#id", SqlDbType.Int);
commanddelete.Parameters["#id"].Value = Int32.Parse(customerID);

Query Won't Work in ASP.net

I am trying to hide this button if the query result is = to btn1.CommandArgument.
The query works, because I have tested it, but the whole solution is not work.
If I replace
myCommand.ExecuteScalar().ToString()
in the if statement to the query result, the button is hidden.
I have looked several times, but can't find any problems. Thank you.
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
Button btn1 = (Button)e.Item.FindControl("addFollowerButton");
// request Query string
var querystring = Request.QueryString["ProjectId"];
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string select = "Select ProfileId from Project_Follower Where ProjectId = #ProjectId";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(select, myConnection);
myCommand.Parameters.AddWithValue("#ProjectId", querystring);
myCommand.ExecuteScalar();
if (myCommand.ExecuteScalar().ToString() == btn1.CommandArgument.ToString())
{
Button hdn = (Button)e.Item.FindControl("addFollowerButton");
btn1.Visible = false;
}
}
}
You need to execute the .ExecuteScalar() call only once! Grab the result (of type object) and then check to make sure it's not null and if it is, call .ToString() on it and compare to the other string you want to check against:
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(select, myConnection);
myCommand.Parameters.AddWithValue("#ProjectId", querystring);
object result = myCommand.ExecuteScalar();
if (result != null && result.ToString().Equals(btn1.CommandArgument.ToString()))
{
Button hdn = (Button)e.Item.FindControl("addFollowerButton");
btn1.Visible = false;
}
}

Categories