Well I have tried all you people suggested but the problem remain same
let me tell you in brief:
Form Name : AuzineForum.aspx
Has 1 GridView which displays all the field from the database using select * from QF
its working good , index is also working , the gridView Has Button and onClick I open new Form AuzineForumAnswer.aspx ..OK
I want to pick one record from AuzineForum.aspx and display on AuzineForumAnswer.aspx as well as it happens here in http://stackoverflow.com (we click on threads then the new page opens which has the question and answer on which we clicked previous) ...ok
so On AuzineForum.aspx's Button the code is
Button lb = (Button)sender;
GridViewRow row = (GridViewRow)lb.NamingContainer;
if (row != null)
{
int index = row.RowIndex; //gets the row index selected
Label AID1 = (Label)ForumQuesView.Rows[index].FindControl("AID1");
Label AID2 = (Label)ForumQuesView.Rows[index].FindControl("AID2");
Label AID3 = (Label)ForumQuesView.Rows[index].FindControl("AID3");
HyperLink Question = (HyperLink)ForumQuesView.Rows[index].FindControl("Question");
Label Questiontags = (Label)ForumQuesView.Rows[index].FindControl("Questiontags");
Label Askedby = (Label)ForumQuesView.Rows[index].FindControl("Askedby");
Response.Redirect(String.Format("AuzineForumAnswer.aspx?Question=" + Question.Text + "&Questiontags=" + Questiontags.Text + "&Askedby=" + Askedby.Text + "&AID1=" + AID1.Text + "&AID2=" + AID2.Text + "&AID3=" + AID3.Text, Server.UrlEncode(Question.Text), Server.UrlEncode(Questiontags.Text), Server.UrlEncode(Askedby.Text), Server.UrlEncode(AID1.Text), Server.UrlEncode(AID2.Text), Server.UrlEncode(AID3.Text)));
I had passes so many many parameter becuase of accuracy......
Now when I run it and click on the button so its open AuzineForumAnswer.AuzineForumAnswerand shows that record very well but problem occurs when the qtags field has "#" type of data like here tags( C#, GridView, etc) so, when the tags field has the data includin "#" chracter then it gives "Object refrence not set to Instance of an object " and if the qtags has normal data like ( specialcharacter gridview sql C ) then it open AuzineForumAnswer.aspx and show data without error
the code behind of AuzineForumAnswer.aspx is below
protected void GetAllData()
{
string connection = System.Configuration.ConfigurationManager.ConnectionStrings["AuzineConnection"].ConnectionString;
using (SqlConnection sqlconn = new SqlConnection(connection))
{
using (SqlCommand sqlcomm = sqlconn.CreateCommand())
{
sqlcomm.CommandText = "Select * From QF where Question='" + Server.UrlDecode(Request.QueryString["Question"].ToString()) + "' And qtags='" + Server.UrlDecode(Request.QueryString["Questiontags"].ToString()) + "' And UserFullName='" + Server.UrlDecode(Request.QueryString["Askedby"].ToString()) + "' And AID1='" + Server.UrlDecode(Request.QueryString["AID1"].ToString()) + "' And AID2='" + Server.UrlDecode(Request.QueryString["AID2"].ToString()) + "' And AID3='" + Server.UrlDecode(Request.QueryString["AID3"].ToString()) + "'";
SqlDataAdapter sda = new SqlDataAdapter(sqlcomm);
DataTable dt = new DataTable();
sda.Fill(dt);
try
{
sqlconn.Open();
ForumQuesView.DataSource = dt;
ForumQuesView.DataBind();
ForumQuesView.AllowPaging = true;
}
catch (Exception ex)
{
Status.Text = ex.Message.ToString();
}
}
}
}
NOW I ALSO DO NOT UNDERSTAND What the problem here because only qtags and question is two field in which user allows to store data as they want, the question is text and qtags and all are the char field but problem is not in database the problem is here with the character #
Try changing your sql statement to include parameters and see if that works.
What you have now is not only difficult to maintain and causes errors but it’s prone to SQL injection attack quite easily.
sqlcomm.CommandText = "Select * From QF where Question=#Question And qtags=#Qtags And UserFullName=#UserName And AID1=#AID1 And AID2=#AID2 And AID3=#AID3";
sqlcomm.Parameters.Add(new SqlParameter("#Question", Server.UrlDecode(Request.QueryString["Question"])));
sqlcomm.Parameters.Add(new SqlParameter("#Qtags", Server.UrlDecode(Request.QueryString["Questiontags"])));
sqlcomm.Parameters.Add(new SqlParameter("#UserName", Server.UrlDecode(Request.QueryString["Askedby"])));
sqlcomm.Parameters.Add(new SqlParameter("#AID1", Server.UrlDecode(Request.QueryString["AID1"])));
sqlcomm.Parameters.Add(new SqlParameter("#AID2", Server.UrlDecode(Request.QueryString["AID2"])));
sqlcomm.Parameters.Add(new SqlParameter("#AID3", Server.UrlDecode(Request.QueryString["AID3"])))
;
As I know the query is fine even if you using # in the condition.
I doubt for a moment, then I tried this query
Select * From QF where Question='question 1'
And qtags='tag #1';
those query still run smooth and return the record.
Related
I have two dropdownlists one of the country (worlddrdolist) and the another is of states (staatddl) and the button (NumOfUsrBtn) where if the user since click on it then the label will show the total sum of users depending on a country selected from (worlddrdolist) First whatever if the user select the state or not also if the user select the state then it will show the users depending of the country , the below code need update and fix some of part as i tried my best to fix but i coundnt, and i am receiving error message:
"Must declare the scalar variable "#cou"." also "Must declare the
scalar variable "#sta"."
protected void NumOfUsrBtn_Click(object sender, EventArgs e)
{
using (var conn = new SqlConnection(sc))
{
string UsrNumSQL = "SELECT COUNT (UsrID)FROM UserInfo WHERE 1=1 AND Country = #cou AND State=#sta";
using (var cmd = new SqlCommand(UsrNumSQL, conn))
{
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 10000;
cmd.Parameters.AddWithValue("#cou", worlddrdolist.SelectedValue);
cmd.Parameters.AddWithValue("#sta", staatddl.SelectedValue);
string condition = "";
if (worlddrdolist.SelectedValue != "")
{
condition += " and Country='" + worlddrdolist.SelectedValue + "'";
}
if (staatddl.SelectedValue != "")
{
condition += " and State='" + staatddl.SelectedValue + "'";
}
cmd.Connection.Open();
NumbOfUsersLbl.Text = cmd.ExecuteScalar().ToString();
}
}
}
This is not how parameterized queries works.
You need add your parameter value as a parameter in your command, not an additional condition.
cmd.Parameters.AddwithValue("#cou", worlddrdolist.SelectedValue);
cmd.Parameters.AddwithValue("#sta", staatddl.SelectedValue);
But I strongly suspect you just wanna add additional conditions with AND... at first place, you don't need to use parameter in your command at all. Looks like your conditions is not known at compile time, instead you wanna build them in runtime.
In such a case, just delete unnecessary parts in your query since you wanna add them based on your condition like;
string UsrNumSQL = "SELECT COUNT (UsrID)FROM UserInfo WHERE 1=1";
...
...
if (worlddrdolist.SelectedValue != "")
{
condition += " and Country='" + worlddrdolist.SelectedValue + "'";
}
if (staatddl.SelectedValue != "")
{
condition += " and State='" + staatddl.SelectedValue + "'";
}
cmd.Connection.Open();
NumbOfUsersLbl.Text = cmd.ExecuteScalar().ToString();
I have a User privilege form, where I load grid from Administrator table, then I insert data from GridView with a Checkbox property in a new User table in database, it works perfectly.
But in next condition I want to load grid from both of two tables, first User table where the data is shown with Checkbox checked true property, and the second Administrator table, where data is shown with check box checked false property.
If u understand my question, so please help me.
My Code is:
protected void CmdUserRights_Click(object sender, ImageClickEventArgs e)
{
StrSql = "Select Name from Sys.tables";
StrSql = StrSql + " Where Name='" + "User_" + CboUserId.Text + "'";
DataSet rs = (DataSet)MethodClass.ConnectionToQuery(StrSql);
if (rs.Tables[0].Rows.Count <= 0)
{
StrSql = "Select * from User_Administrator";
StrSql = StrSql + " Order by serial_no asc";
DataSet rs2 = (DataSet)MethodClass.ConnectionToQuery(StrSql);
GvUserPrivilege.DataSource = rs2.Tables[0];
GvUserPrivilege.DataBind();
}
else
{
StrSql = "Select * from " + "[User_" + CboUserId.Text + "]";
StrSql = StrSql + " Order By serial_no asc ";
DataSet rs4 = (DataSet)MethodClass.ConnectionToQuery(StrSql);
if (rs4.Tables[0].Rows.Count > 0)
{
GvUserPrivilege.DataSource = rs4.Tables[0];
GvUserPrivilege.DataBind();
foreach (GridViewRow rows in GvUserPrivilege.Rows)
{
CheckBox ChkBoxRows = (CheckBox)rows.FindControl("chk");
ChkBoxRows.Checked = true;
}
}
else
{
}
}
}
Agree with Alex Bell.
Try to join tables like this:
SELECT
Administrator.*,
(User.somefield IS NOT NULL) checked
FROM Administrator
LEFT JOIN User
ON [join condition here]
If some record exists in User table, then expression (User.somefield IS NOT NULL) will be true (you need to use some NOT NULL column for this). Otherwise, it will be false.
So I have been browsing stack overflow and MSDN and cannot find a control (or make sense of the ones I have) to access the data directly of a detailsview. I'm in C# using a .Net WebApplication.
I think what I am looking for is the equivalent in gridview is row.Cells[1].Value can anybody help with the accessor to the DetailsView cells?
What I am trying to do is to access the exact data values I have bound to the DetailsView1
.Text is sufficient for all the numbers and string (only two shown for example) but not for the timestamp MTTS (a datetime) as it lost the milliseconds and the code (SQL query) I use after it cannot find the correct values in the db without the milliseconds. Will I also need to change the way I have bound the data, or some setting to give the bound data millisecond accuracy?
Code example:
Decimal RUN_ID = 0;
DateTime MTTS = new DateTime();
foreach(DetailsViewRow row in DetailsView1.Rows)
{
switch(row.Cells[0].Text)
{
case "RUN_ID":
RUN_ID = Decimal.Parse(row.Cells[1].Text);
break;
case "MTTS":
MTTS = DateTime.Parse(row.Cells[1].ToString());
break;
}
}
I have tried
row.Cells[1].ID = "MTTS";
MTTS = (DateTime)((DataRowView)DetailsView1.DataItem)["MTTS"];
But it does not recognize the MTTS and I am not sure how to set the parameter I have tried a few different things already with no success.
The workaround was messy, essentially I rebuilt the query that gathered the data to the GridView and then I made a function to grab the MTTS directly using LinQ and the parameteres from inside the GridView which assigns the MTTS as a DateTime.
This was in my opinion a bad way of doing things but it worked. I would prefer a better solution.
MTTS = GetMTTS(JOB_PLAN, JOB_NAME,JOB_NAME_ID,RUN_ID,JOB_STATUS);
public DateTime GetMTTS(string JOB_PLAN, string JOB_NAME, string JOB_NAME_ID, Decimal RUN_ID, string JOB_STATUS){
string myEnvName = XXX;
TableName = XXX.ToString();
ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings[myEnvName].ToString();
string thisRUN_ID = RUN_ID.ToString();
cmdText = #"SELECT MTTS FROM " + TableName +
" WHERE JOB_PLAN = '" + JOB_PLAN + "'"
+ " AND JOB_NAME = '" + JOB_NAME + "'"
+ " AND JOB_NAME_ID = '" + JOB_NAME_ID + "'"
+ " AND RUN_ID = '" + thisRUN_ID + "'"
+ " AND JOB_STATUS = '" + JOB_STATUS + "'";
DataSet ds = new DataSet();
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
try
{
SqlCommand SQLcc = new SqlCommand(cmdText,conn);
SqlDataReader reader;
reader = SQLcc.ExecuteReader();
while (reader.Read())
{
MTTS = reader.GetDateTime(0);
}
reader.Dispose();
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
}
return MTTS;
}
SOLVED: I figured out my own issue. It was working as I thought. I just was not reading the correct row.
I am trying to update a few columns in a row, in the Table [Profiles]. I don't get any errors when running this code but it doesn't actually update the columns. I have never used an update before. What am I doing wrong.
string currentPage = Request.Url.ToString();
Uri myUri = new Uri(currentPage);
string position = HttpUtility.ParseQueryString(myUri.Query).Get("position");
string electionYear = HttpUtility.ParseQueryString(myUri.Query).Get("year");
var finalkey = Session["Userid"].ToString() + "^" + position + "^" + electionYear;
string sqlquery = "UPDATE [Profiles] SET Qualifications=#Qualifications, Platform=#Platform, FamilyLife=#FamilyLife, Website=#Website where FinalKey=#FinalKey";
SqlConnection conn = new SqlConnection(dbLocation);
SqlCommand comm = new SqlCommand(sqlquery, conn);
try
{
conn.Open();
comm.Parameters.AddWithValue("#FinalKey", finalkey);
comm.Parameters.AddWithValue("#Qualifications", qualificationsBox.Text);
comm.Parameters.AddWithValue("#Platform", platformBox.Text);
comm.Parameters.AddWithValue("#FamilyLife", familyBox.Text);
comm.Parameters.AddWithValue("#Website", candWebsiteBox.Text);
comm.ExecuteNonQuery();
}
catch { }
conn.Close()
Please refer the value of finalkey by set break Point ! Only Possible for Not Updating is,
There is no matching record found with this finalkey value.
another option
set where class value manually Like where finalvalue="user1dec" and check if it is work, then u can........
var finalkey = Session["Userid"].ToString() + "^" + position + "^" + electionYear;
I am trying to bind sql data on textboxes against reading data from label my code is as below:
string sql1 = " select openbal from AccountMast where accname='" + comboBox1.Text + "' and companyID='" + label4.Text + "'";
SqlDataAdapter dap1 = new SqlDataAdapter(sql1, con);
DataSet ds1 = new DataSet();
dap1.Fill(ds1);
for (int p = 0; p < ds1.Tables[0].Rows.Count; p++)
{
if (label11.Text == "Dr")
{
txtopenbaldr.Text = Convert.ToString(ds1.Tables[0].Rows[p]["openbal"]);
}
if (label11.Text == "Cr")
{
txtopenbalcr.Text = Convert.ToString(ds1.Tables[0].Rows[p]["openbal"]);
}
}
//Label11 Bind by Sql.
string sql10 = " select obcat from AccountMast where accname='" + comboBox1.Text + "' and companyID='" + label4.Text + "'";
SqlDataAdapter dap10 = new SqlDataAdapter(sql10, con);
DataSet ds10 = new DataSet();
dap10.Fill(ds10);
for (int p = 0; p < ds10.Tables[0].Rows.Count; p++)
{
label11.Text = Convert.ToString(ds10.Tables[0].Rows[p]["obcat"]);
}
The label11 bound by sql data and it should display text "Dr" OR "Cr" at a time.
but it's not working as the label11.text not support for bind the data onto textboxes
I have two textboxes as below:
Opening Balance/Debit Opening Balance/Credit
txtopenbaldr.Text txtopenbalcr.Text
There are two textboxes which can databind on above condition: Remember only one textbox should be bind as per condition.
I am trying the trick but it's fail. Suggest the solution.
I'm assuming that you simply appended the code for label11.text at the end of your message, but that in reality label11.text is assigned before you try to set txtopenbaldr.Text or txtopenbalcr.Text.
If that's the case, I would make sure that label11.Text actually has the value Dr or Cr, and not DR or CR, as the comparisons will be case-sensitive.