Quantcast
Channel: DataSource Controls - SqlDataSource, ObjectDataSource, etc.
Viewing all 956 articles
Browse latest View live

How do you retrieve a control value in a FormView onItemUpdating?

$
0
0

I want to update the users email address in an asp.net identity table when saving. The issue that I see is in the method UserProfileFormView_ItemUpdating. I am not able to retrieve the new entered value in the TextBox with ID="email_txt". How do you get the value?

Thanks in advance

Brad

<asp:FormView ID="FormView1" runat="server" DataKeyNames="Id" DataSourceID="ProfileEDS" DefaultMode="Edit" OnItemUpdating="UserProfileFormView_ItemUpdating"><EditItemTemplate><asp:TextBox ID="firstName_txt" runat="server" Text='<%# Bind("firstName") %>'></asp:TextBox><asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="firstName_txt" ErrorMessage=" - first name is required" CssClass="text-danger small" Display="Dynamic"></asp:RequiredFieldValidator><asp:TextBox ID="lastName_txt" runat="server" Text='<%# Bind("lastName") %>'/><asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="lastName_txt" ErrorMessage=" - title is required" CssClass="text-danger small" Display="Dynamic"></asp:RequiredFieldValidator><asp:TextBox ID="email_txt" runat="server"  /><asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="email_txt" ErrorMessage=" - email is required" CssClass="text-danger small" Display="Dynamic"></asp:RequiredFieldValidator><asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="Update" CssClass="btn btn-primary" /><asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False" Text="Cancel" CssClass="btn btn-default" OnClick="UpdateCancelButton_Click" /></EditItemTemplate></asp:FormView><asp:EntityDataSource ID="EntityDataSource1" runat="server" ConnectionString="name=modelContainer" DefaultContainerName="modelContainer" EnableFlattening="False" EntitySetName="UserProfiles" EnableUpdate="true" Where="it.[Id] = @nId"><WhereParameters><asp:QueryStringParameter Name="nId" QueryStringField="profileid" DbType="Int32" /></WhereParameters></asp:EntityDataSource>

Code Behind C#

    protected void UserProfileFormView_ItemUpdating(object sender, FormViewUpdateEventArgs e)
    {
        TextBox emailTxt = (TextBox)UserProfileFormView.Row.FindControl("email_txt");
        string email = emailTxt.Text;

        UserManager Manager = new UserManager();
        var user = Manager.FindById(userId);

        user.Email = email.ToString();

        var result = Manager.Update(user);

    }


How to use parameter with IN operator in SQL query

$
0
0

I am trying to use a parameter in a query in conjunction with an IN operator.  I'm finding that the query works when the parameter works out to as single value...

EOOI

...returning the expected dataset but when the parameter works out to be multiple values...

All, Customer Service, EOOI, Finance, Supply Chain

...the result set is returned empty.  There is no sql exception thrown just no result set returned.  The value of the parameter is built by loading the content of the items  of  a dropdownlist into a string and then loading the string into the parameter (if the 'All' option of the dropdownlist is selected) or just using the one selected value of the dropdownlist (if the 'All' selection of the dropdownlist is not selected).

My code is below...Can someone kindly show me what I need to do to get this to work?  Thanks tonnes for any help, Roscoe

The parameter is @YTDChartOBU .  The Query looks like...

           string query = "with" +
                            " CTE_Amount as" +
                            " (" +
                            " select CAST([Initiative] AS NVARCHAR(MAX)) as Initiative, sum(Amount) as TotalAmount" +
                            " from SavingsDetail where Year = @YTDChartYear" +
                            " and CAST([Originating_Business_Unit] AS NVARCHAR(MAX)) in (@YTDChartOBU)" +
                            " and Month between @YTDChartStartMonth and @YTDChartEndMonth" +
                            " group by CAST([Initiative] AS NVARCHAR(MAX))" +
                            " )," +
                            " CTE_Baseline as" +
                            " (" +
                            " select CAST([Initiative] AS NVARCHAR(MAX)) as Initiative, sum(BaselineAmount) as TotalBaselineAmount" +
                            " from Baselines where Year = @YTDChartYear" +
                            " and CAST([Originating_Business_Unit] AS NVARCHAR(MAX)) in (@YTDChartOBU)" +
                            " group by CAST([Initiative] AS NVARCHAR(MAX))" +
                            " )" +
                            " select" +
                            " coalesce(a.Initiative, b.Initiative) as Initiative," +
                            " IsNull(a.TotalAmount, 0)," +
                            " IsNull(b.TotalBaselineAmount, 0)" +
                            " from CTE_Amount as a" +
                            " full join CTE_Baseline as b" +
                            " on b.Initiative = a.Initiative" +
                            " order by" +
                            " Initiative";

...YTDChartOBU is dropdownlist and the build of the parameter @YTDChartOBU looks like...

                String Y = YTDChartYear.Text;
                String S = YTDChartStartMonth.Text;
                String E = YTDChartEndMonth.Text;
                String B = YTDChartOBU.Text;
                String Bx = "";

                try
                {
                    cmd.Parameters.Add("@YTDChartYear", SqlDbType.Int).Value = Y;
                    cmd.Parameters.Add("@YTDChartStartMonth", SqlDbType.Int).Value = S;
                    cmd.Parameters.Add("@YTDChartEndMonth", SqlDbType.Int).Value = E;
                    if (B == "All")
                    {
                        foreach (ListItem li in YTDChartOBU.Items)
                        {
                            Bx = Bx + li.Value + ", ";
                        }
                        Bx = Bx.TrimEnd(' ');
                        Bx = Bx.TrimEnd(',');
                        cmd.Parameters.Add("@YTDChartOBU", SqlDbType.NVarChar).Value = Bx;
                    }
                    else
                    {
                        cmd.Parameters.Add("@YTDChartOBU", SqlDbType.NVarChar).Value = B;
                    }             
                    DataTable dt = new DataTable();
                    using (SqlDataAdapter sda = new SqlDataAdapter())
                    {
                        cmd.CommandType = CommandType.Text;
                        cmd.Connection = cn;
                        sda.SelectCommand = cmd;
                try
                {
                        sda.Fill(dt);
                }
                catch (Exception ex)
                {
                    // Handle the error
                    if (ex.Source != null)
                        Console.WriteLine("IOException source: {0}", ex.Source);
                    throw;
                }

Sql - This doesn't make any senseSqlDataSource1.SelectCommand = "select * from perfumes where marca=? and genero='Masculino' order by preco ASC"; SqlDataSource1.SelectParameters.Add("@ff", Request.QueryString["marca"]);

$
0
0

Hi 

This sql works for me:

SqlDataSource1.SelectCommand = "select * from perfumes where marca=? and genero='Masculino' order by preco ASC";
SqlDataSource1.SelectParameters.Add("@ff", Request.QueryString["marca"]);

This sql doesn't work. It returns no rows, why?

string sexo = "Masculino";
        SqlDataSource1.SelectCommand = "select * from perfumes where marca=? and genero=? order by preco ASC";
        SqlDataSource1.SelectParameters.Add("@ff", Request.QueryString["marca"]);
        SqlDataSource1.SelectParameters.Add("@genero", sexo);

DatatList sqlsource

Both DataSource and DataSourceID are defined on 'Gridview1'

$
0
0

Hi ..

I am receiving the error "Both DataSource and DataSourceID are defined on 'Gridview1'" and I know It is because of using DataSourceId in Gridview and defining datasource in code behind .. but I can not fix it!

Please help.

My code is as follows:

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DefaultConnection %>"
SelectCommand="SELECT * FROM [Ads] WHERE UserName = @UserName" DataSourceMode="DataSet">
<SelectParameters>

<asp:SessionParameter Name="UserName" SessionField="UserName" Type="String" />
</SelectParameters>
</asp:SqlDataSource>

<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" AllowPaging="true" PageSize="5" AllowSorting="true" AutoGenerateColumns="false" AutoGenerateSelectButton="true" EmptyDataText="No Value">
<Columns>
<asp:BoundField DataField="AdTitle" HeaderText="AdTitle" SortExpression="AdTitle" />
<asp:BoundField DataField="AdCategory" HeaderText="AdCategory" SortExpression="AdCategory" />
<asp:BoundField DataField="AdDescription" HeaderText="AdDescription" SortExpression="AdDescription" />
<asp:ImageField DataImageUrlField="Value" ControlStyle-Height="100" ControlStyle-Width="100" />

</Columns>
<SelectedRowStyle BackColor="Beige" ForeColor="Red" />
<AlternatingRowStyle BackColor="Aqua"/>
<PagerSettings FirstPageText="Home" LastPageText="Last" Mode="NumericFirstLast" />
</asp:GridView>

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            string[] filePaths = Directory.GetFiles(Server.MapPath("~/Images/"));
            List<ListItem> files = new List<ListItem>();
            foreach (string filePath in filePaths)
            {
                string fileName = Path.GetFileName(filePath);
                files.Add(new ListItem(fileName, "~/Images/" + fileName));

            }

            GridView1.DataSource = files;
            GridView1.DataBind();
        }
        
        SqlDataSource1.SelectParameters["UserName"].DefaultValue = User.Identity.Name;
    }

OledbConnection.Close() taking too long to execute

$
0
0

I am using oledb to read data from excel file.

Everything is fast but when I am closing the connection its taking too much time.

Incorrect syntax near '1'.

$
0
0

Im trying to make a webpage where they user is able to register their own account and also at the same time another table is being updated. Ignore all the // :P

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["LoginConn"].ConnectionString);
SqlCommand cmd = new SqlCommand();
string sql = "INSERT INTO userInfo(userTitle,userFirstName,userLastname";
sql += ",userNric,userEmail,userAddress1";
sql += ",userAddress2,userZipcode,userMobile";
sql += ",userPhone,userName,userPassword";
sql += ",userRole)";
sql += "VALUES(@userTitle,@userFirstName,@userLastName,@userNric,@userEmail,@userAddress1,@userAddress2,@userZipcode,@userMobile,@userPhone,@userName,@userPassword,@userRole)";
cmd.CommandText = sql;
cmd.Connection = con;
con.Open();
cmd.Parameters.AddWithValue("@userTitle", rbMr.Text);
cmd.Parameters.AddWithValue("@userFirstName", tbFirstName.Text);
cmd.Parameters.AddWithValue("@userLastName", tbLastName.Text);
cmd.Parameters.AddWithValue("@userNric", tbNric.Text);
cmd.Parameters.AddWithValue("@userEmail", tbEmail.Text);
cmd.Parameters.AddWithValue("@userAddress1", tbAddress1.Text);
cmd.Parameters.AddWithValue("@userAddress2", tbPassword.Text.Trim());
cmd.Parameters.AddWithValue("@userZipcode", tbAddress2.Text);
cmd.Parameters.AddWithValue("@userMobile", int.Parse(tbMobileNum.Text));
cmd.Parameters.AddWithValue("@userPhone", int.Parse(tbPhoneNumber.Text));
cmd.Parameters.AddWithValue("@userName", tbUsername.Text.Trim());
cmd.Parameters.AddWithValue("@userPassword", tbPassword.Text.Trim());
cmd.Parameters.AddWithValue("@userRole", "Customer");


cmd.ExecuteNonQuery();


// SqlCommand id = new SqlCommand("SELECT max(UserID) FROM UserInfo");

// TODO 1. select max(UserID) query to read the max id from the UserInfo table
// 2. use a data reader to "loop" the result from the above query
//string maxID = "";
// 3. store the result of the reader into maxID;
// 2. use a data reader to "loop" the result from the above query
//string maxID = "";
// 3. store the result of the reader into maxID;
// id.Connection = con;

DataTable dt = new DataTable();
SqlCommand cd = new SqlCommand();
cd.Connection = con;
string sql1 = "SELECT max(UserID) From UserInfo";
cd.CommandText = sql1;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cd;
da.Fill(dt);
cd.ExecuteNonQuery();

Session.Add("max(UserID)", dt.Rows[0][0].ToString());
string id = Session["max(UserID)"].ToString();

// string strCommandText = "SELECT max(UserID) From UserInfo";
//SqlCommand cc = new SqlCommand(strCommandText, con);
//cc.Connection = con;
//cc.ExecuteScalar();


SqlCommand myConn = new SqlCommand();
string oo = "INSERT INTO UserD(UserID,ABalance,LBalance,HDay,1day,2day) VALUES (@ID,@Ab,@Lb,@Hd,@1d,@2d)";
myConn.CommandText = oo;
myConn.Connection = con;
myConn.Parameters.AddWithValue("@ID", id);
myConn.Parameters.AddWithValue("@Ab", 500);
myConn.Parameters.AddWithValue("@Lb", null);
myConn.Parameters.AddWithValue("@Hd", null);
myConn.Parameters.AddWithValue("@1d", null);
myConn.Parameters.AddWithValue("@2d", null);

myConn.ExecuteNonQuery();

try
{
lbMessage.Text = "Register Completed";
btnContinue.Visible = true;

}
catch (Exception ex)
{
lbMessage.Text = ex.Message;
//throw new Exception(ex.Message);
}
con.Close();

Confused about open and close connection

$
0
0

HI there ,I'm developing a website and bout its connections I've confused.

below are my code to open and execute queries please give me your advice ,thanks.

 protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                Commands cmd = new Commands();
                Allusers = cmd.AllUsers();
                using (DataSet ds = cmd.SelectReadyCampaign(User.Identity.Name))
                {
                    if (ds.Tables.Count - 1 >= 0)
                    {
                        LSTCampaign.DataSource = ds.Tables[0];
                        LSTCampaign.DataBind();
                    }
                }

                using (DataSet ds = cmd.SelectCampaignReportByDay())
                {
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        hidXCategories1 = hidXCategories1 + dr["ParticipatedDate"].ToString() + ",";

                    }
                    foreach (DataRow dr1 in ds.Tables[0].Rows)
                    {
                        hidValues1 = hidValues1 + dr1["participation"].ToString() + ",";

                    }
                }

                hidValues1 = hidValues1.TrimEnd(',');
                hidXCategories1 = hidXCategories1.TrimEnd(',');
                Ranks = new decimal[4];
                Ranks=cmd.SelectUserRank(User.Identity.Name);
                ReadyCampaign = cmd.SelectCountReadyCampaign();
            }
        }

public class Commands : BasePage
{
    DataSet DS;

    public Commands()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    public int AllUsers()
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            Con.Open();
            cmd.Connection = Con;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "[UserAccount].[AllUsers]";
            cmd.Parameters.Add("@Allusers", SqlDbType.NVarChar, 100).Direction = ParameterDirection.Output;
            cmd.ExecuteNonQuery();
            int Exists = int.Parse(cmd.Parameters["@Allusers"].Value.ToString());
            Con.Close();
            return Exists;
        }
    }
    public DataSet SelectReadyCampaign(string UserName)
    {
        DataSet DS = new DataSet();

        using (SqlDataAdapter da = new SqlDataAdapter("[app].[SelectReadyCampaign]", Con))
        {
            Con.Open();
            da.SelectCommand.CommandType = CommandType.StoredProcedure;
            da.SelectCommand.Parameters.AddWithValue("@Username", UserName);
            da.Fill(DS, "table");
            Con.Close();
            return DS;
        }
    }
    public DataSet SelectCampaignReportByDay()
    {
        DataSet DS = new DataSet();

        using (SqlDataAdapter da = new SqlDataAdapter("[UserAccount].[SelectCampaignReportByDay]", Con))
        {
            Con.Open();
            da.SelectCommand.CommandType = CommandType.StoredProcedure;

            da.Fill(DS, "table");
            Con.Close();
            return DS;
        }
    }
    public decimal[] SelectUserRank(string UserName)
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            Con.Open();
            cmd.Connection = Con;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "[UserAccount].[SelectUserRank]";
            cmd.Parameters.AddWithValue("@UserName", UserName);

            cmd.Parameters.Add("@UserLevel", SqlDbType.NVarChar, 100).Direction = ParameterDirection.Output;
            cmd.Parameters.Add("@UserPoints", SqlDbType.NVarChar, 100).Direction = ParameterDirection.Output;
            cmd.Parameters.Add("@UserPotintP", SqlDbType.NVarChar, 100).Direction = ParameterDirection.Output;
            cmd.Parameters.Add("@UserRankPoint", SqlDbType.NVarChar, 100).Direction = ParameterDirection.Output;
            cmd.ExecuteNonQuery();
            decimal[] report = new decimal[4];
             report[0] = decimal.Parse(cmd.Parameters["@UserLevel"].Value.ToString());
             report[1] = decimal.Parse(cmd.Parameters["@UserPoints"].Value.ToString());
             report[2] = decimal.Parse(cmd.Parameters["@UserPotintP"].Value.ToString());
             report[3] = decimal.Parse(cmd.Parameters["@UserRankPoint"].Value.ToString());
             Con.Close();
             return report;
        }
    }
    public int SelectCountReadyCampaign()
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            Con.Open();
            cmd.Connection = Con;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "[App].[SelectCountReadyCampaign]";
            cmd.Parameters.Add("@Count", SqlDbType.NVarChar, 100).Direction = ParameterDirection.Output;
            cmd.ExecuteNonQuery();
            int Count = int.Parse(cmd.Parameters["@Count"].Value.ToString());
            Con.Close();
            return Count;
        }
    }
}
public class BasePage:System.Web.UI.Page
{
    //public static Commands db = new Commands();
    public static SqlConnection Con;
    private string ConString;
    public static string MessageComment;
	public BasePage()
	{
        ConString = System.Configuration.ConfigurationManager.ConnectionStrings["FlyConnection"].ToString();
        Con = new SqlConnection(ConString);
        //Con.Close();
        //Con.Open();I opened my connection like this in the past.
	}
}

in some cases I receive closed connection issue and other things,are my code above correct or they need to be fixed somehow.

please give me your advise.

thanks


Connection.close slow using OleDb

$
0
0

We're developing an n-tier application, using an Access database. We're basically finished with the application, but we're optimising some of the slower pages. Using a profiler and a timer measuring the time spent in rendering, sql and framwork parts of the application we tracked down the lackluster performance to the places where we we called connection.close()(in the try-catch-finally).

If we drop the close statement, performance is many times faster:

Using try-catch-finally and connection.close()
SQL statements: 245
SQL executiontime: 614ms
Framework execution time:11461ms
Page rendering :94ms
Total execution time:11555ms

Without connection.close()
SQL statements: 245
SQL executiontime: 559ms
Framework execution time:1447ms
Page rendering :117ms
Total execution time:1564ms

Any suggestions on why this is happening?

Global Replace of Connection String value in a Dataset.xsd file

$
0
0

I'm updating an app that uses several typed data sets, each of which points to one of three sql data bases:  DB1, DB2, DB3.

I'm going to merge the three DBs into DB_ALL, and create a new connection string to it.

When that's done, I'd like some way of editing the datasets to use the new connection string, so I don't have to recreate them (agh!)

I'm thinking I might be able to do a find/replace all on the .XSD file for the datasets, to replace the old connection string name with the new one.

Will this work, or are there other issues that I need to consider?

How to monitor SQL jobs using C#

$
0
0

Hi

I have a task to monitor the SQL jobs.

I wish to do with this with C# or asp.net application.

the task is.. I've send a mail to specific user once the job fails.

so how can I do this.. 

please help me to finish this..

Thanks

Koushik

SQL increment decimal number by 1

$
0
0

Hello world

Can anyone advise how I would increase the following number 00103379.00002  by 1 so it looks like this 00103379.00003.

my select i tried is : select max(Number) + 1 as NxtNumber  from table  Or select max(Number) + '1' as NxtNumber  from table

Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the nvarchar value '00103379.00002' to data type int.

Any help is appreciated.

Beginner Question on DataSet and TableAdapter

$
0
0

Hello,

I am beginning to use a DataSet to access a SQL database.

There is a table of rooms:

idx          int
organisation int
name         varchar(50)
type         char(1)

Now I would like to have a method that retrieves a set of rooms, like this:

DataTable getRooms(int organisation,String type);

I know that I can create a new query that uses parameters:

SELECT * FROM rooms WHERE (organisation=@organisation AND type=@type);

But in this case, the WHERE-condition always contains all attributes (organisation and type). But sometimes I would like to search all rooms with a certain type, where the organisation does not matter. In this case, I would pass -1 as the organisation.

What I need is something like this:

DataTable getRooms(int organisation,String type);
{
 String condition = "";

 if (organisation != -1)
  condition += "organisation=" + organisation;

 if (type != null)
 {
  if (condition != "")
   condition += " AND ";
  condition += "type='" + type + "'";
 }

 DataTable t = GetDataByCondition (condition);
 return (t);
}

Can I do this somehow?

Thank you

Magnus

Best practice for loading/saving database records in a form

$
0
0

Hello,

in the context of database driven applications you always have the need for web pages with the following life cycle:

  1. open and load a record
    I like to use a parameter in the query string to specify the record's primary key, e. g. "?idx=1234".
    However, when this parameter is missing, I interpret this as "new record".
  2. let the user edit the record
    In this phase you may react on the user events, e. g. enable or disable fields depending on the values of other fields.
  3. save the record
    Write the record into the database. If the key was specified, this will be an UPDATE. If not, it's a new record and you will do an INSERT.

However, I find myself realizing those steps in an inconsistent manner, applying totally different concepts for loading and saving.

  • load
    It's very elegant to declare a SqlDataSource right in the aspx file. I declare it with a parameter "idx", while attaching this parameter to the query string.
    Then I simply fetch the data out of it:
    DataView dtv = (DataView) myDataSource.Select(DataSourceSelectArguments.Empty);
    DataRowView drv = dtv[0];
    String name = drv["Name"].ToString();
  • save
    The other direction is totally different: I instantiate a database connection and execute SQL statements:
    SqlConnection con = new SqlConnection(connectionString);
    con.Open();
    String sql="INSERT INTO myTable (atr1,atr2,atr3) VALUES (" + var1 + "," + var2 + ",'" + var3 + "')";
    cmd = new SqlCommand(sql, con);
    cmd.ExecuteNonQuery();
    con.Close();

Then, I found that my aspx page "forgets" the key value (idx) on postback. So I added a hidden field that I explicitely assign the index value again on postback. This is getting worse when I use UserControls as sub forms. I won't go into further details...

I am looking for an elegant method to do this loading and saving stuff. With "elegant", I mean less bloated code, preferrably in a declarative way.

What are the concepts that you are using? Are there any examples on this topic out there?

Thanks
Magnus

Grid veiw row select and update and insert in checkbox list itme more than (3 chcekbox)

$
0
0

 protected void Button1_Click(object sender, EventArgs e)
    {
        string diaryno = getvalue("select max(letter_current_diary_no) as letter_current_diary_no from offices where office_code = '" + Session["user_code"].ToString() + "'");

                string offcode = GetOfficecode("select OFFICE_CODE from USERS where USER_CODE='" + Session["user_code"].ToString() + "'");
              
                foreach (GridViewRow row in GridView1.Rows)
                {
                    if (row.RowType == DataControlRowType.DataRow)
                    {
                       
                        CheckBox myCheckBox = row.FindControl("cbSelect") as CheckBox;
                        if (myCheckBox.Checked == true)
                        {
                            Label lblid = row.FindControl("lblid") as Label;
                          
                            
                            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
                            try
                            {

                                int i = 0;

                               
                                if (con.State == ConnectionState.Closed)
                                    con.Open();
                                SqlTransaction trn = con.BeginTransaction();

                                string cmdText1 = "update lettertrans set NEXT_OFFICE_CODE =@NEXT_OFFICE_CODE ,desp_date=@desp_date, desp_time= @desp_time,Desp_flag=@Desp_flag,next_office_receipt_status=@next_office_receipt_status,despatch_date_time=@despatch_date_time ,Transit_flag=@Transit_flag,Remarks=@Remarks where id=@id" ;
                                SqlCommand cmd2 = new SqlCommand(cmdText1, con, trn);
                               cmd2.Parameters.AddWithValue("@id",  lblid.Text.Trim());
                               // cmd2.Parameters.AddWithValue("@diary_no", row.Cells[4].Text);
                              //  cmd2.Parameters.AddWithValue("@office_code", offcode);
                                cmd2.Parameters.AddWithValue("@NEXT_OFFICE_CODE", CheckBoxList.SelectedValue);
                                cmd2.Parameters.AddWithValue("@desp_date", DateTime.Now);
                                cmd2.Parameters.AddWithValue("@desp_time", DateTime.Now);
                                cmd2.Parameters.AddWithValue("@Desp_flag", "1");
                                cmd2.Parameters.AddWithValue("@next_office_receipt_status", "0");
                                cmd2.Parameters.AddWithValue("@despatch_date_time", DateTime.Now);
                                cmd2.Parameters.AddWithValue("@Transit_flag", "1");
                                cmd2.Parameters.AddWithValue("@Remarks", txtremarks.Text);
                                i = cmd2.ExecuteNonQuery();
                                
                                if (i >=0)
                                {
                                    i = 0;

                                    string str = "insert into lettertrans (file_letter, letter_office_code, letter_diary_no,PREV_OFFICE_CODE,PREV_OFFICE_DIARY_NO,  receipt_date, receipt_time,  receipt_flag, transit_flag, receipt_date_time, is_new, ad_file_code,next_office_code,ns_file_code,   desp_date, desp_time, desp_flag, next_office_receipt_status,despatch_date_time,comments )  values(@file_letter,@letter_office_code,@letter_diary_no,@PREV_OFFICE_CODE,@PREV_OFFICE_DIARY_NO, @receipt_date, @receipt_time, @receipt_flag, @transit_flag,@receipt_date_time, @is_new,@ad_file_code,@next_office_code,@ns_file_code, @desp_date, @desp_time,@desp_flag,@next_office_receipt_status,@despatch_date_time,@comments)";
                                   // string str = "insert into lettertrans(diary_no,office_code)values (@diary_no,@office_code)";
                                    SqlCommand cmdlt = new SqlCommand(str, con, trn);
                                    {
                                       // cmdlt.Parameters.AddWithValue("@id",lblid.Text );
                                        cmdlt.Parameters.AddWithValue("@FILE_LETTER", "L");
                                        cmdlt.Parameters.AddWithValue("@LETTER_OFFICE_CODE", row.Cells[2].Text);
                                        cmdlt.Parameters.AddWithValue("@letter_diary_no", row.Cells[4].Text);
                                       cmdlt.Parameters.AddWithValue("@PREV_OFFICE_CODE", offcode);
                                        cmdlt.Parameters.AddWithValue("@PREV_OFFICE_DIARY_NO", diaryno);
                                      //  cmdlt.Parameters.AddWithValue("@diary_no", diaryno);
                                       // cmdlt.Parameters.AddWithValue("@OFFICE_CODE", offcode);
                                        cmdlt.Parameters.AddWithValue("@RECEIPT_DATE", System.DateTime.Now.ToString("yyyy-MM-dd "));
                                        cmdlt.Parameters.AddWithValue("@RECEIPT_TIME", System.DateTime.Now.ToString("yyyy-MM-dd "));
                                        cmdlt.Parameters.AddWithValue("@RECEIPT_FLAG", "1");
                                        cmdlt.Parameters.AddWithValue("@transit_flag", "1");
                                        cmdlt.Parameters.AddWithValue("@Receipt_Date_Time", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                                        cmdlt.Parameters.AddWithValue("@is_new", "1");
                                        cmdlt.Parameters.AddWithValue("@ad_file_code", "L");
                                        cmdlt.Parameters.AddWithValue("@ns_file_code", "SL");
                                        cmdlt.Parameters.AddWithValue("@next_office_code", CheckBoxList.SelectedValue);
                                        cmdlt.Parameters.AddWithValue("@next_office_receipt_status", "0");
                                        cmdlt.Parameters.AddWithValue("@DESP_Date", System.DateTime.Now.ToString("yyyy-MM-dd"));
                                        cmdlt.Parameters.AddWithValue("@DESP_Time", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                                        cmdlt.Parameters.AddWithValue("@DESP_flag", "0");
                                     cmdlt.Parameters.AddWithValue("@despatch_date_time", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                                     cmdlt.Parameters.AddWithValue("@comments", txtremarks.Text);
                                    i = cmdlt.ExecuteNonQuery();

                                     if (i >= 0)
                                        {
                                            i = 1;
                                        }
                                    }
                               }

                                else
                                {
                                    throw new Exception("Insertion Failed");
                                }
                                if (i == 1)
                                {
                                    trn.Commit();
                                    BindData();
                                    ClientScript.RegisterStartupScript(this.GetType(), "Alert", "alert('Letter dispatch successfully...');", true);
                                }
                                else
                                {
                                    trn.Rollback();
                                    ClientScript.RegisterStartupScript(this.GetType(), "Alert", "alert('Failed');", true);
                                }
                            }
                            catch (Exception ex)
                            {
                                ClientScript.RegisterStartupScript(this.GetType(), "Alert", string.Format("alert('" + ex.Message + "');"), true);
                            }
                            finally
                            {
                                if (con.State == ConnectionState.Open)
                                    con.Close();
                            }
                        }
                    }
                }
                BindData();
    }


How to lookup a label for a value from a lookup table?

$
0
0

Hello,

I have a DataSet with a TableAdapter for rooms with the following attributes:

idx int
name varchar(50)
type char(1)

The column type references a table of types:

symbol  name
-----------------------
K   kitchen
C   conference
O   office
...

I have bound the DataSet to an ObjectDataSource which is used by a ListView.

Within the ListView, I have the ItemTemplate:

<ItemTemplate><td align="left" style="" runat="server"><asp:Label ID="lbl_Index" runat="server" Text='<%# Eval("idx") %>' /></td><td align="left" style="" runat="server"><asp:Label ID="lbl_Name" runat="server" Text='<%# Eval("name") %>' /></td><td align="left" style="" runat="server"><asp:Label ID="lbl_Type" runat="server" Text='<%# Eval("type") %>' /></td></ItemTemplate>

However, the "type" is shown by its symbol, not by its name.
I would like it to be shown by its name.

I have tried to define the TableAdapter with a view instead of a table. But then there are no insert statements generated.

What would be a simple way to lookup the name "on the fly" in the aspx-page?

Thanks

Yeoman

GridView updating

$
0
0

hi,

i have a GridView in which i can edit the contents as usual and it is ok. but my problem is when updating some values it requires some calculations with other tables in which i have another SqlDatasource connected with a Repeater.

how can i make my GridView after updating, refresh the other DataSource automatically in which the calculations also will be updated with the new values of my GridView items.

below image is more clear

DataBinder in Hyperlink

$
0
0

H all, this is the first time I cam e across this. I am trying to create a hyperlink for a field in a Data Table, should be easy right?  However I have a file path to append in the front of my database field and I cannot get it to show on my web page. I am not getting any errors, its just not showing. Heres my markup:

<!-- HyperLink--><div class="form-group"><label for="hyprlnkChecklist" class="control-label col-xs-2">Checklist</label><div class="col-xs-7"><asp:HyperLink ID="hyprlnkChecklist" runat="server"></asp:HyperLink></div></div>

Heres my code behind: (unfortunately its in VB, lol)

 Dim filePath As String = "\\myserver\root\folder1\folder2\"

/* Im retrieving a bunch of Rows from my database and loading a form on a page with them, I want to make this fields a hyperlink that goes to a folder on my Network, All of the share permissions are set up already, I just cannot get this to render as a hyperlink*/

  hyprlnkChecklist.NavigateUrl = String.Format(filePath & DataBinder.Eval(dt.Rows(0).Item("CheckList")))

not sure why it doesn't like the Eval : getting error, Overload resolution failed because no accessible 'Eval' accepts this number of arguments.

creating updateparameters by code

$
0
0

Hi all:

I want to know if it is possible to create a parameter of a updateparameters of a objectdatasource by code, dynmically, and how to do that.

TIA

wrong number of parameters?

$
0
0

Hi all:

I have an objectdatasource

<asp:ObjectDataSource ID="objdsseguimientos" TypeName="comercial.seguimientos_administracion" SelectCountMethod="seleccionar_cuenta" EnablePaging="true" SelectMethod="seleccionar_todo" UpdateMethod="actualizar_todo" StartRowIndexParameterName="comienzo" MaximumRowsParameterName="maximonumeroregistros" SortParameterName="orden" runat="server" ><SelectParameters><asp:Parameter Name="condicion" DefaultValue=" "  /></SelectParameters><UpdateParameters><asp:Parameter Name="pedido" /><asp:Parameter Name="obra"  /></UpdateParameters></asp:ObjectDataSource>

If I put only a parameter in updateparameters it works. But if I put two parameters it doesn't.

What is wrong?

TIA

Viewing all 956 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>