Search from SqlDataSource show in Gridview asp.net c# - c#

I have problem about my label is not lost when search data that have in SQL Server.
Here is my code
protected void btnSearchAll_Click(object sender, EventArgs e)
{
// BindAbb();
string search1 = txtSearch.Text;
string Filter = "";
if (SqlDataSource1.SelectCommand.Contains(String.Empty))
{
lblOutput.Visible = true;
lblOutput.Text = "Not Found";
}
if (search1 != "")
{
Filter = Filter + "AbbCode like '%" + search1 + "%' and ";
}
if (Filter.Length > 0)
{
string finalFilter = Filter.Remove(Filter.Length - 4, 3);
SqlDataSource1.FilterExpression = finalFilter;
}
else
{
lblOutput.Visible = false;
grd_AbbCode.DataBind();
}
}
}
When I search data that don't have in SQL Server, it's ok when "Not Found" is show on my page.
http://www.mx7.com/i/ece/0u4iX8.jpg
but when I search data that I do have in SQL Server, "Not found" is still show together with my data.
http://www.mx7.com/i/125/AxrUNz.jpg
I solve it in my way but it still show.
How to solve it? Thank you so much.

Related

Retrieve data datagrid to form

I have created a form to insert data. When data inserted it shows into datagridview1. I use dataGridView1_MouseClick event to retrieve data into the form. I successfully retrieved textbox data only into my form. I want to retrieve checkbox value which is checked or not. How can i retrieve checkbox value by clicking dataGridView1_MouseClick event.
I use following code for that:
private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
try
{
txtID.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
Name.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
}
catch (ApplicationException ex)
{
MessageBox.Show("Error: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
}
My result is here
But I want like this:
U can retrive values of other fields in similar like u did
This is for WPF control Checkbox link
I assume checkbox name of movie is movie_chbox
movie_chbox.IsChecked =
dataGridView1.SelectedRows[0].Cells[3].Value.toString() == "1" ?true:false
Similarly you can do same for other too.
This is for winforms control Checkbox link
movie_chbox.Checked =
dataGridView1.SelectedRows[0].Cells[3].Value.toString() == "1" ?true:false
Instead of displaying 0 or 1 in datagridview display "Interested"/"Not Interested" and when you insert/update to database that time insert/update as 0 or 1 for better database mentainance.
Use the checked property of the check box control in your code and change the code for different categories. In your case the final code will be be something like below:
private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
try
{
txtID.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
txtName.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
string isCheckedMovie = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
string isCheckedSports = dataGridView1.SelectedRows[0].Cells[3].Value.ToString();
string isCheckedReading = dataGridView1.SelectedRows[0].Cells[4].Value.ToString();
string isCheckedWriting = dataGridView1.SelectedRows[0].Cells[5].Value.ToString();
if (isCheckedMovie == "1")
movieBox.Checked = true;
else
movieBox.Checked = false;
if (isCheckedSports == "1")
sportsBox.Checked = true;
else
sportsBox.Checked = false;
if (isCheckedReading == "1")
readingBox.Checked = true;
else
readingBox.Checked = false;
if (isCheckedWriting == "1")
writingBox.Checked = true;
else
writingBox.Checked = false;
}
catch (ApplicationException ex)
{
MessageBox.Show("Error: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}

I have a validation that stops the user navigating to the next window but when all fields are cleared goes to the next window

I am working on a project and I am trying to get my Navigation button to recognise when values already stored are cleared from the clear all fields button made. Its fine when I do not enter any values the first time but if I type them in and store them then clear all fields I press the navigation button then I progress onto the window without entering any details. Is there a way to solve this?
here is my code:
thank you.
private void clear_Click(object sender, RoutedEventArgs e)
{
//clears all fields to start again on enetring your details
if (SCNResult.Text == String.Empty || Nameresult.Text == String.Empty)
{
MessageBox.Show("You need to enter your details and store them before pressing this button");
return;
}
Nameresult.Text = " ";
box.Text = "";
namebox.Text = "";
SCNResult.Text = " ";
error.Text = " ";
//
}
/////END OF BUTTON////
private void comp_Click(object sender, RoutedEventArgs e)
{
// This instruction stops the user from continuing if they have not entered their details.
if (SCNResult.Text == String.Empty || Nameresult.Text == String.Empty)
{
MessageBox.Show("You need to enter your details before progressing to the next window");
return;
}
else
{
computing Nav1 = new computing();
Nav1.Show();
this.Close();
}
//end of instruction
//navigates to the next window
//
}
When you clear the fields:
Nameresult.Text = " "; //here is the problem
box.Text = "";
namebox.Text = "";
SCNResult.Text = " "; //here is the problem
error.Text = " ";
" " is not an empty string, that's why your if always return false

Check if record already exists within the database

I have a program that allows users to enter in movies and details about that movie and store them in a database. I have the database being displayed in my C# program and the user can select one of the rows and the information from that row will be put into the text box it corresponds to, for example the Title will go in the title text box and so on. what I want to do is stop the user hitting the submit button and putting the same record in the database.
Any help would be appreciated
Submit button:
private void btnSubmit_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(txtTitle.Text) || string.IsNullOrWhiteSpace(txtRunTime.Text))
{
MessageBox.Show("Fill in all the required fields");
}
else
{
if (lstStatus.SelectedIndex == 0)
{
Status = "Watched";
}
else
{
Status = "Not Watched";
}
if (lstType.SelectedIndex == 0)
{
Type = "Movie";
}
else
{
Type = "TV Show";
}
con.Open();
SqlCommand cmd = new SqlCommand("insert into dbo.Movies(Title, Genre, RunTime, Type, Status) values('"+txtTitle.Text+"','"+txtGenre.Text+"','"+txtRunTime.Text+"','"+Type+"','"+Status+"')", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Data transferred into the database!");
con.Close();
txtTitle.Text = "";
txtRunTime.Text = ""; /
}
}
Code when selecting a row:
private void DataGridMovies_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if(DataGridMovies.CurrentRow.Index == DataGridMovies.Rows.Count - 1)
{
MessageBox.Show("Empty row selected"); // Display a message to the user
}
else
{
ID = Convert.ToInt32(DataGridMovies.Rows[e.RowIndex].Cells[0].Value.ToString());
txtTitle.Text = DataGridMovies.Rows[e.RowIndex].Cells[1].Value.ToString();
txtGenre.Text = DataGridMovies.Rows[e.RowIndex].Cells[2].Value.ToString();
txtRunTime.Text = DataGridMovies.Rows[e.RowIndex].Cells[3].Value.ToString();
if (DataGridMovies.Rows[e.RowIndex].Cells[4].Value.ToString() == "Movie")
{
lstType.SelectedIndex = 0;
}
else
{
lstType.SelectedIndex = 1;
}// End of IF ELSE Statement
if (DataGridMovies.Rows[e.RowIndex].Cells[5].Value.ToString() == "Watched")
{
lstStatus.SelectedIndex = 0;
}
else
{
lstStatus.SelectedIndex = 1;
}// End of IF ELSE Statement
}//End of IF statement
You need to use sql parameters or your sql database can be hacked.
You can read about that here:
https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.parameters?view=netframework-4.8
cmd.Parameters.AddWith(name, value)
Determine if the record exists. If it does not you are adding it with insert. If not you update the record instead.
Depending on the process power you have at your disposal you might also look into autocomplete. This can hide the fact they are just updating a record you already "found".
https://www.grapecity.com/blogs/dynamic-autocomplete-c1textbox
Meta tagging and algorithms on the back end sometimes take care of duplicate entries.

Problems with textboxes and page load in C#

Okay here I have some code from my project at the moment.
Basically the user goes onto the page and their current password is in the password textbox, and their avatar is selected in the droplist.
They can change their password by editing the text in the textbox and change their avatar by selecting a new one from the list. This is then written to the file where this information is kept. It writes to the file okay, but it writes what was initially in the textbox and droplist.
If i comment out these lines in the page load:
avatarDropList.SelectedValue = Session["avatar"].ToString();
newPasswordTextbox.Text = Session["password"].ToString();
It updates the file properly, but this is not what I want as I want the old password displayed there initially as well as the avatar to be selected in the dropbox.
Code below:
public partial class TuitterProfile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
avatarImage.ImageUrl = "~/images/avatars/" + Session["avatar"] + ".gif";
avatarDropList.SelectedValue = Session["avatar"].ToString();
userNameTextbox.Text = Session["user"].ToString();
newPasswordTextbox.Text = Session["password"].ToString();
}
protected void okButton_Click(object sender, ImageClickEventArgs e)
{
string username = Session["user"].ToString();
string password = Session["password"].ToString();
string newPassword = newPasswordTextbox.Text;
string newAvatar = avatarDropList.SelectedValue;
int allDataReference = -1;
//Each element in the array is a string(Username Password Avatar)
string[] allData = File.ReadAllLines(Server.MapPath("~") + "/App_Data/tuitterUsers.txt");
for (int i = 0; i < allData.Length; i++)
{
string[] user = allData[i].Split(' ');
if (user[0] == username && user[1] == password)
{
allDataReference = i;
}
}
if (allDataReference > -1)
{
Session["avatar"] = newAvatar;
Session["password"] = newPassword;
allData[allDataReference] = username + " " + newPassword + " " + newAvatar;
File.WriteAllLines(Server.MapPath("~") + "/App_Data/tuitterUsers3.txt", allData);
}
}
}
In the ASP.Net page event lifecycle, Page_Load is called on every request. What you are doing here is resetting the value of the TextBox every time the page loads, which will include the time that you press the button to save the profile.
All you need to do is check for the current request being a postback when you set your initial values:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
avatarImage.ImageUrl = "~/images/avatars/" + Session["avatar"] + ".gif";
avatarDropList.SelectedValue = Session["avatar"].ToString();
userNameTextbox.Text = Session["user"].ToString();
newPasswordTextbox.Text = Session["password"].ToString();
}
}

How to display error lines from a gridview?

I have these codes for uploading csv file. Also, I have put a GridView to display its contents. Now, what I want to do is to display error lines from the GridView, for example, if there are missing words in a particular column or row, I would want to display that that particular line is empty, and that the user has to reupload with that particular line updated. The thing is, I'm really new with this, I hope someone could help me! I do not know how to retrieve the error lines and display it on the website. These are my codes :
protected void btnUpload_Click(object sender, EventArgs e)
{
string strFileNameOnServer = fileUpload.PostedFile.FileName;
string fileExt =
System.IO.Path.GetExtension(fileUpload.FileName);
if (fileUpload.PostedFile != null && fileExt == ".csv")
{
try
{
//fileUpload.PostedFile.SaveAs(ConfigurationManager.AppSettings + appDataPath + "\\" + strFileNameOnServer);
fileUpload.PostedFile.SaveAs(Server.MapPath("~/Uploaded"));
//string appPath = HttpContext.Current.Request.ApplicationPath;
// string physicalPath = HttpContext.Current.Request.MapPath("~/MajorProject");
Label1.Text = "File name: " +
fileUpload.PostedFile.FileName + "<br>" +
fileUpload.PostedFile.ContentLength + " kb<br>" +
"Content type: " +
fileUpload.PostedFile.ContentType;
}
catch (Exception ex)
{
Label1.Text = "Error saving <b>" + strFileNameOnServer + "</b><br>. " + ex.Message;
}
BtnImport1.Visible = true;
Cancel.Visible = true;
fileUpload.Visible = false;
btnUpload.Visible = false;
}
else
{
Label1.Text = "Error - a file name must be specified/only csv files are allowed";
return;
}
var data = File.ReadAllLines(Server.MapPath("~/Uploaded"))
.Select(line => line.Split(','))
.Select(columns => new {GuestName = columns[0], Guest_ID = columns[1], IC_Number = columns[2]});
myGridView.DataSource = data;
myGridView.DataBind();
}
Do I have to add new items into my aspx file? Like a label to display the error lines? The contents of the csv file has Name, Ic Number and also House. If so, can anyone show me the codes to do this?
You could check for missing values on GridView.RowDataBound event for yours myGridview.
Example:
void myGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Check if any of the values of mygridview row cells are empty.
if (e.Row.Cells[0].Text == "")
{
e.Row.Cells[0].Text = "ERROR: Guest name is empty!"
e.Row.Cells[0].Attributes.CssStyle.Add(HtmlTextWriterStyle.Color, "red");
}
if (e.Row.Cells[1].Text == "")
{
e.Row.Cells[1].Text = "ERROR: Guest Id is empty!"
e.Row.Cells[1].Attributes.CssStyle.Add(HtmlTextWriterStyle.Color, "red");
}
if (e.Row.Cells[2].Text == "")
{
e.Row.Cells[2].Text = "ERROR: Ic number is empty!"
e.Row.Cells[2].Attributes.CssStyle.Add(HtmlTextWriterStyle.Color, "red");
}
}
}
Don't forget to declare it inside gridview properties:
<asp:GridView ID="myGridview"
runat="server"
OnRowDataBound="myGridView_RowDataBound">
</asp:GridView>

Categories