how can I get table name from using a textbox [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Is it possible to make a select query using a textbox as a reference.
Some like:
SELECT modeltype FROM txt_model.text
The value display in the textbox is the name of the table.

You could do it as described, but it is a bad idea. I suggest code like the following -- it is safe and has the same UI:
// add your table names to the list below
List<string> validTables = New List<string>() {"users", "addr", "events" };
if (validTables.IndexOf(txt_model.text.ToLower()) > 0)
{
// use "SELECT modeltype FROM "+txt_model.text to perform work
}
else
{
// error code
}
It might be that you want a dynamic list of validTables. In that case you could take the result of (with SQL Server as an example):
SELELCT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
And put it in the validTables list.
Or you could just put the result of that select in a drop down.

One way to build your query string:
string sql = string.Format("Select modeltype From {0}", txt_model.Text);
// ...
SqlCommand cmd = new SqlCommand(sql);

Related

How to get MAX value from a database table in c# with where clause [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am trying to get the row data from the database table to a label the condition is I want the highest value column to be displayed in the label with other fields currently my code is :
private void electionWinner()
{
try
{
conn.Open();
string qry = "SELECT * FROM Results WHERE (SELECT MAX(Results) FROM Results) ";
SqlCommand cmd = new SqlCommand(qry,conn);
string result = cmd.ExecuteReader().ToString();
winnerlbl.Text = result.ToString();
}
catch (SqlException es)
{
MessageBox.Show($"{es}");
}
}
}
I am currently new to c# and trying to understand it, so I am lost, thanks in advance.
The query itself isn't correct. here's why:
you did not state which column in the Results table that you want
the max of
When you adjust the select statement inside the where clause, you need to make sure your WHERE statement will either give you a true or false, currently all it does is get the max value (if you correctly add the column name)
select * from Results where COLUMNNAME= (select Max(COLUMNNAME) from Results)
Always make sure to run the query on the database before doing it inside your code
Use ORDER BY and LIMIT:
SELECT r.*
FROM Results r
ORDER BY r.Results DESC
LIMIT 1;
You can modify your query like below
`string qry = "Select ColumnName From Results where ColumnName in (SELECT Max(ColumnName) FROM Results)";`

C# MySQL table entry counting from user selection [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I tried to write a code which will count rows in MySQL , same as combobox-selected text.
For example in my MySQL database,i have a table(ogrencikayit) and in this table i have several columns.In my combobox there are 2 different selection which allows to select student class.When user select the class in combobox , label has to show count of total student in selected class.Here is my code;
DB database = new DB();
int kayitsayisi = -1;
MySqlCommand cmd = new MySqlCommand("Select count(*) from ogrencikayit Where ogrsinif ="+comboBox3.Text.ToUpper()+"" , database.baglanti);
database.baglanti.Open();
kayitsayisi = Convert.ToInt32(cmd.ExecuteScalar());
string kayitt = kayitsayisi.ToString();
label24.Text = kayitt;
Shortly; i try to find a code that it will read the name of the class name from combobox than it will search in database that how many student belongs to that class and it will show it to the label.
It says Invalid column "class name" in where clause.
that's cause you are missing single quote around the value and thus it's taking it as a column name. it should be like below
Where ogrsinif ='"+comboBox3.Text.ToUpper()+"'"
Again, always use parameterized query instead of concatenating your user input.
MySqlCommand cmd = new MySqlCommand("Select count(*) from ogrencikayit Where ogrsinif = #ogrsinif" , database.baglanti);
cmd.Parameters.Add("#ogrsinif", SqlDbType.VarChar).Value=comboBox3.Text;

How to execute sql user defined function using c#? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
how to execute sql user defined function using c# same as that of executing stored procedure
You can use it like any other sql. Here's an example:
using (var con = new SqlConnection(Properties.Settings.Default.ConnectionString))
using (var cmd = new SqlCommand("SELECT dbo.IsInteger(#value);", con))
{
con.Open();
cmd.Parameters.Add("#value", SqlDbType.VarChar).Value = "10";
bool isInt = (bool)cmd.ExecuteScalar();
}
dbo.IsInteger is a scalar-valued function which returns a bit(true/false).
For the sake of completeness and even if it's not really related, here is it:
CREATE Function [dbo].[IsInteger](#Value VarChar(18))
Returns Bit
As
Begin
Return IsNull(
(Select Case When CharIndex('.', #Value) > 0
Then Case When Convert(int, ParseName(#Value, 1)) <> 0
Then 0
Else 1
End
Else 1
End
Where IsNumeric(#Value + 'e0') = 1), 0)
End

Cannot implicitly convert type 'int' to 'string' ? c#4 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
while running the given below code, getting an error. I have to perform delete operation through gridview.
code:
protected void gvEdit_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string Emp_ID = gvEdit.DataKeys[e.RowIndex].Value.ToString();
int EId = Convert.ToInt32(Emp_ID); // error popup here
ShadingAnalysisDataSetTableAdapters.tbl_EmployeeToTeamTableAdapter tm;
tm = new ShadingAnalysisDataSetTableAdapters.tbl_EmployeeToTeamTableAdapter();
DataTable dt = new DataTable();
tm.GetDelete(EId);
BindData();
}
DB:
SQL:
DELETE FROM tbl_EmployeeToTeam WHERE (Emp_ID = #Emp_ID)
I assume that GetDelete expects a string but you're passing an int. I think so because it seems to be the parameter for Emp_ID which is a varchar. So you could simply pass that string which you already had in:
gvEdit.DataKeys[e.RowIndex].Value.ToString();
But if it's supposed to be an int, why don't you use the correct data type in the database?
Bad habits to kick : choosing the wrong data type
Update
My employee Id is strating from EMP001, EMP002..etc. So how can I use
integer data type
Why do you store always EMP at the beginning? You could also omit that and use int as type which would be more efficient and fail-safe. Then you could prepend EMP where you need to display it.
However, if you don't want to change that and Emp_ID contains only the ID without EMP you can use string concatenation:
tm.GetDelete("EMP" + Emp_ID);

How should I design the stored proc and c # method to get such results [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a problem here.
In c# code I am constructing a method called
saveImages(Guid ImageId, String url, byte[] imageData) which calls a stored procedure to store the data on a sql server.
I understand all the process of how to construct a stored procedure and call it from c# code.
My question is, now I want the code to behave in such a way that if save successfully return the imageId otherwise return null.
How should I construct the stored procedure? How do I set the parameters?
And how do I get the returned value in C#?
Thanks
As already mentioned, you start by adding:
SELECT SCOPE_IDENTITY();
at the end of your Stored Procedure.
Your method should look something like:
public int saveImages(Guid ImageId, String url, byte[] imageData)
{
using (SqlCommand command = new SqlCommand() {
Connection = your connection,
CommandType = CommandType.StoredProcedure,
CommandText = "your Stored Procedure"
})
{
try
{
command.Parameters.AddWithValue(...); // Add your Parameters here
return (int)command.ExecuteScalar();
}
catch
{
return 0;
}
}
}

Categories